AbsolutePickle42
AbsolutePickle42

Reputation: 61

Godot: Raycast2D not casting to correct position

I have a raycast2d node that I want to cast to where the player clicks, but when I click it still casts but not to the right place.

My code is just $RayCast2D.set_cast_to(fire_position), fire_position being where the mouse clicks.

Can anyone help?

Upvotes: 0

Views: 1195

Answers (2)

David Elias
David Elias

Reputation: 1

It sounds like the issue may be with how you are determining the 'fire_position' variable. Without more information about how that variable is being set, it's difficult to me sayed for certain what the problem is.

However, you can try to debug the issue by printing out the 'fire_position' variable to the console before passing it to the RayCast2D.set_cast_to() method, to check if it's the correct position where the mouse clicked. Also, make sure that you have set the correct orientation of the RayCast2D node, so it is pointing in the direction you want to cast the ray.

Upvotes: 0

Theraot
Theraot

Reputation: 40285

The RayCast2D expects a vector on its own local coordinates.

Presumably you got the position of the mouse click in global coordinates. Then you would convert it to the local space of the RayCast2D like this:

$RayCast2D.set_cast_to($RayCast2D.to_local(fire_position))

I'll also remind you that if you are updating raycast and checking it right away, without a physics frame passing, your will have an stale result. To fix that you can call force_raycast_update on it.

Upvotes: 0

Related Questions