Player position does not change

Godot Version

v4.3

Question

@onready var ray_cast_2d: RayCast2D = $RayCast2D

var playerPos

func _ready() -> void:
	playerPos = get_tree().get_first_node_in_group("player").position

func _physics_process(_delta: float) -> void:
	aim()


func aim():
	playerPos = get_tree().get_first_node_in_group("player").position
	print(playerPos)
	ray_cast_2d.target_position = playerPos

I am trying to make my enemy aim at the player with a raycast, but the raycast doesn’t move at all. So I added print(playerPos) which prints the same x, y every time it triggers even if I move around. How do I get it to always check the players current position?

Maybe try

get_tree().get_first_node_in_group("player").global_position

?

1 Like

I tried that, the same thing happens.

1 Like

Can you provide an image of your sceneTree?

image
image

This is my enemy and my main scene tree. Don’t worry about the detection area, I haven’t coded it yet.

For this line, could you try

ray_cast_2d.target_position = to_local(playePos)

Also turn this on(if you haven’t already) so you can see the raycast

Not quite sure why the position will always be the same

why do you even need a special property for player position?
why not to set property directly?

ray_cast_2d.target_position=get_tree().get_first_node_in_group("player").position

if you use get_first_node_in_group() just for addressing one single node in group from any place, try to for instance use one of Engine’s already used singletons like IP to set meta with a player node id like
in player node:
func _ready(): IP.set_meta(&'player', self)
in your func aim():
ray_cast_2d.target_position=IP.get_meta(&'player').position
this will make player instance available from any script
Engine’s singletons are initialized before static func _static_init()

IP.get_meta(&‘player’).position could be irrelevant to ray_cast_2d if player and raycast have different parents, if so, use .global_position

ray_cast_2d.target_position=ray_cast_2d.to_local(IP.get_meta(&'player').global_position)

common error to use to_local() without setting to local regard of what
ray_cast_2d.target_position=ray_cast_2d.to_local()

1 Like

That worked, thanks! Still learning, so I don’t really understand why this works instead of what I did.

sometimes variable=value returns a copy of data not a reference, that where problem can appear