NavigationAgent2D always moving toward bottom right

Godot Version

4.2.1

Question

Hello,

I’m working on this game and I don’t know why the NavigationAgent2D always moves toward bottom right. So I did a blank project to test it properly and reproduced it. Here is a video and the code I used

extends CharacterBody2D
func _ready():
	$CollisionShape2D/Sprite2D/NavigationAgent2D.target_position = Vector2(20, 30)
func _physics_process(delta):
	velocity = $CollisionShape2D/Sprite2D/NavigationAgent2D.get_next_path_position().normalized() * 100
	move_and_slide()

Video here on reddit → https://www.reddit.com/r/godot/comments/1alodo5/navigationagent2d_always_moves_toward_bottom_right/

Any idea on how to make the NavigationAgent2D.get_next_path_position() reach its target ?

Thanks for your help !

The get_next_path_position() function returns the next global position of the current navigation path. You can not normalize a position and expect things to work, it is not a direction or velocity vector. So what you want to do is use e.g. direction_to() between your characters global position and the next path position and use that to calculate your new velocity for the CharacterBody2D.

I’m getting the same behavior using direction_to. Here is the code and the output, which looks more accurate.

extends CharacterBody2D


# Called when the node enters the scene tree for the first time.
func _ready():
	$CollisionShape2D/Sprite2D/NavigationAgent2D.target_position = Vector2(20, 30)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
	print(global_position.direction_to($CollisionShape2D/Sprite2D/NavigationAgent2D.get_next_path_position()))
	velocity = global_position.direction_to($CollisionShape2D/Sprite2D/NavigationAgent2D.get_next_path_position()).normalized() * 100
	move_and_slide()

Capture d’écran 2024-02-08 à 11.25.05

Seems like the issue is because of something else. I don’t understand the character is not moving toward the next_path_position knowing no other function call is made outside of this one

I’ve found out the problem. I wasn’t having a TileMap under. Awkardly, it should have some sort of map with collisions to be able to use NavAgent. It’s working now