Godot Version
4.2.1
Question
I’m trying to use the example code provided here: 2D navigation overview
But when I try to set the navigation target to a random point, the point is never reached and the character walks forever until they disappear off-screen. Some coordinates work and some don’t, and I can’t find a rhyme or reason to why this is. Even if the character manages to reach a point, if I try to get them to return to the point they came from the same issue happens (point_reached returns false and they walk off forever). I used the ruler tool to make sure the points I choose are within the viewable area, and there are no obstacles that need to be navigated around.
Modified example script:
extends Node2D
var movement_speed: float = 100.0
var movement_target_position: Vector2 = Vector2(512,200)
var point_reached = false
@onready var navigation_agent: NavigationAgent2D = $CharacterBody2D/NavigationAgent2D
func _ready():
# These values need to be adjusted for the actor's speed
# and the navigation layout.
navigation_agent.path_desired_distance = 4.0
navigation_agent.target_desired_distance = 4.0
# Make sure to not await during _ready.
call_deferred("actor_setup")
func actor_setup():
# Wait for the first physics frame so the NavigationServer can sync.
await get_tree().physics_frame
# Now that the navigation map is no longer empty, set the movement target.
set_movement_target(movement_target_position)
func set_movement_target(movement_target: Vector2):
navigation_agent.target_position = movement_target
func _physics_process(delta):
var current_agent_position: Vector2 = global_position
var next_path_position: Vector2 = navigation_agent.get_next_path_position()
print(current_agent_position) #this never updates for some reason
if navigation_agent.is_navigation_finished():
$CharacterBody2D/AnimatedSprite2D.play("idle")
point_reached = true
return
$CharacterBody2D.velocity = current_agent_position.direction_to(next_path_position) * movement_speed
$CharacterBody2D.move_and_slide()
$CharacterBody2D/AnimatedSprite2D.play("walk")
if $CharacterBody2D.velocity.x < 0:
$CharacterBody2D/AnimatedSprite2D.flip_h = true
else:
$CharacterBody2D/AnimatedSprite2D.flip_h = false
Scene script:
extends Node2D
# Called when the node enters the scene tree for the first time.
func _ready():
randomize()
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func random_position():
var x = randf_range(48, 400)
var y = randf_range(48, 400)
#var final_pos = Vector2(x, y) #not working for some reason, try to use specific point instead
var final_pos = Vector2(512,265) # ALSO not working, idk why this is
return final_pos
func _on_timer_timeout():
$testwolf.set_movement_target(random_position())