Raycast2D in incorrect position

Godot Version

4.4.1

Question

So in the image here my raycast is in the bottom left when it’s supposed to be in the center of the character i made. I’m using a line to draw the raycast and I’m not sure what’s happening. (also i drew the cursor on where it was approximately as i cant screenshot my cursor)

This is the code in the RayCast 2D:

extends RayCast2D

@onready var ray = $"."
@onready var player = $"../player"
@onready var debugLine = $"../Line2D"


var mechTR = load("res://Assets/Sprites/MechClops/mechClopsTR.png")
var mechTL = load("res://Assets/Sprites/MechClops/mechClopsTL.png")
var mechBR = load("res://Assets/Sprites/MechClops/mechClopsBR.png")
var mechBL = load("res://Assets/Sprites/MechClops/mechClopsBL.png")

func _physics_process(_delta: float):
	# Get the mouse position in global coordinates
	var mouse_pos = get_viewport().get_mouse_position()
	
	ray.target_position = mouse_pos
	set_enabled(true)
	if target_position.x >= 600 and target_position.y <= 450:
		player.texture = mechTR
	elif target_position.x >= 600 and target_position.y >= 450:
		player.texture = mechBR
	elif target_position.x <= 600 and target_position.y <= 450:
		player.texture = mechTL
	elif target_position.x <= 600 and target_position.y >= 450:
		player.texture = mechBL
	
	if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
		ray.collide_with_areas = true
		
		if ray.is_colliding():
			var raycollider = ray.get_collider()
			print(raycollider.name)
		
		ray.collide_with_areas = false

	

	
	
	#if is_colliding():
	#	var collider = get_collider()
	#	
	#	print("AAAAAA: " + collider.name)


func _on_draw() -> void:
	ray.draw_line(Vector2(640, 480), Vector2(ray.target_position), Color.AQUA, -1, false)

Your mouse has a different coordinate system than the raycast. Maybe using to_local would help.

Instead of ray or $"." you can use self or omit the variable entirely as self is implicit.

ray.target_position = self.to_local(mouse_pos)

That seems to have at least made the ray attached to the cursor but it’s still in the bottom right


Is there any coding changing the position of the raycast? Your _on_draw function is also using the raycast’s coordinate system, are you sure it’s taking that into account? Have you tried using Vector2.ZERO for your start position?

oh my mistake yeah i reset the raycast position to Vector2.ZERO and that fixed it. tysm

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.