Trouble Pathfinding

Hello, I am having trouble having my enemy pathfind towards the player. The enemy has a reference to the players global position through a global variable, yet it never updates the values to reflect the current global variable. I.E. the enemies player variable continues to read (0, 0) despite the global variable appropriately being updated to reflect the players current position.

Enemy code w/ pathfinding

extends CharacterBody2D

var move_speed = 50

@onready var player = global_player.player_pos

func _ready():
	call_deferred("actor_setup")

func _physics_process(_delta):
	if !$NavigationAgent2D.is_target_reached():
		var new_point_dir = to_local($NavigationAgent2D.get_next_path_position()).normalized()
		velocity = new_point_dir * move_speed
		print(player)
		move_and_slide()

func actor_setup():
	await get_tree().physics_frame
	$NavigationAgent2D.target_position = player

func _on_timer_timeout():
	if $NavigationAgent2D.target_position != player:
		$NavigationAgent2D.target_position = player
	$Timer.start()

Relevant player code

func _process(_delta):
	global_player.player_pos = global_position
@onready var player = global_player
$NavigationAgent2D.target_position = player.player_pos

this way should work I think

global_player is an node I guess so a reference var
player_posis just a vector 2d value var

when you are passing a reference var “the var will by update over time” bcz it aims to the memory where the object is allocated, if you pass a value var you are just passing some information

array nodes object are reference vars, int float bool value vars

sorry for my bad explaining I’m a begginer too, search value vs reference types variable to understand the difference better

1 Like

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