I am working on an rpg and have the animation tree and stuff all setup and I have a RayCast that will detect if a NPC is in range. I am sure there is a a better way to do what I'm trying to achieve but Googling hasn't found me anything and I'm probably just searching wrong haha.

Here is my code for the movement and what I attempted to do to rotate the RayCast2D to match the players direction.

func _physics_process(delta):
    #Movement
    var input_vector = Vector2.ZERO
    input_vector.x = Input.get_action_strength("right") - Input.get_action_strength("left")
    input_vector.y = Input.get_action_strength("down") - Input.get_action_strength("up")
    input_vector.normalized()
    print(input_vector)

if input_vector != Vector2.ZERO:
	anim_tree.set("parameters/Idle/blend_position", input_vector)
	anim_tree.set("parameters/Walk/blend_position", input_vector)
	anim_state.travel("Walk")
	velocity = velocity.move_toward(input_vector * MAX_SPEED, ACCELERATION * delta)
else:
	anim_state.travel("Idle")
	velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)
velocity = move_and_slide(velocity)

#If player down rotate raycast 0
if input_vector == Vector2(0, 1):
	$RayCast2D.rotate(90)
#If player left rotate raycast 90
elif input_vector == Vector2(-1, 0):
	$RayCast2D.rotate(90)
#If player up rotate raycast 180
elif input_vector == Vector2(0, -1):
	$RayCast2D.rotate(180)
#If Player right rotate raycast 270
elif input_vector == Vector2(1, 0):
	$RayCast2D.rotate(270)

You can convert the Vector2 to an angle using atan2 if you want the raycast to point in exactly the same direction as the player is moving. Something like this should work, I think:

if input_vector.length_squared() != 0:
	var input_angle = atan2(input_vector.y, input_vector.x)
	$Raycast2D.global_rotation = input_angle
2 years later