2D Raycast Not Following Desired Position

Godot Version

Godot 4.2.2 stable

I am trying to create a basic top down shooter and now my goal is to create a simple enemy that walks towards the player but once its raycast finds the player the enemy should stop and fire a projectile, basic long distance enemy. My problem is rotating the raycast so it follows the player position, with my current setup the rotation is very strange (appears to be slow and never truly aiming at the player) and can only collide with the player when really close.

extends RayCast2D

@onready var player = get_node("/root/Main/Player")

var target = player

signal found_target
signal no_target

func _physics_process(_delta):
	target_position = player.global_position
	global_rotation = position.angle_to_point(target_position)
	if is_colliding():
	else: no_target.emit()`

Also, the code I’m building specifically for this is inside a raycast node inside the long distance enemy and I’m signaling to the main node that the raycast has collided. Would like to know if that is the most efficient / best way.

You don’t need to set the rotation, it’s enough to set the target_position, you just have to convert the player’s global position to local coordinates I think:
target_position = to_local(player.global_position)

You are using local position when you should use global position of player.


Thank you, this worked but I was wondering if I can do it without changing the length of the raycast? I planned on having the enemy always aiming towards the player but once the raycast collided (got close enough) the enemy would stop

One way to limit the ray’s length is like this:
target_position = global_position.direction_to(player.global_position) * 200
Where 200 is the length