Get_next_path_position() returns current position

Godot Version

4.2.2

Problem

navigation_agent.get_next_path_position() always returns position of the enemy, NOT the next path position:

(this is enemy code, that should make it follow the player)

extends CharacterBody2D

@export var player: CharacterBody2D
@export var movement_speed: float = 100.0
@onready var navigation_agent: NavigationAgent2D = get_node("NavigationAgent2D")

func _ready() -> void:
	navigation_agent.velocity_computed.connect(Callable(_on_velocity_computed))
	set_movement_target(player.global_position)

func set_movement_target(movement_target: Vector2):
	navigation_agent.set_target_position(movement_target)

func _physics_process(delta):
	set_movement_target(player.global_position)
	if navigation_agent.is_navigation_finished():
		return

	var next_path_position: Vector2 = navigation_agent.get_next_path_position()
	var new_velocity: Vector2 = global_position.direction_to(next_path_position) * movement_speed
	if navigation_agent.avoidance_enabled:
		navigation_agent.set_velocity(new_velocity)
	else:
		_on_velocity_computed(new_velocity)

func _on_velocity_computed(safe_velocity: Vector2):
	velocity = safe_velocity
	move_and_slide()

Few important things

This works:

  • navigation_agent.target_position — when used with print(), prints position of the PLAYER (so the navigation_agent.set_target_position() works)
  • navigation_agent.distance_to_target() — returns distance to the PLAYER (as it should)

this does NOT work:

  • navigation_agent.get_next_path_position() — always returns position of the ENEMY (not the player)
  • navigation_agent.get_final_position() — returns (0, 0)

What I’ve tried

There aren’t many things to try, so I’m stuck.

Conclusion

Any help will be appreciated, thanks in advance.

If there is no valid navigation mesh from a NavigationRegion2D or a TileMap there is no pathfinding so the only thing the NavigationAgent can give is the default which is the current position.

1 Like

Interesting. I’ve added the TileMap with a NavigationLayer and the “Navigation Enabled” enabled for the “terrain” layer. Can you tell me how to add the pathfinding?

Oh, I figured it out by painting the tiles with navigation layer

Your TileMap cells need cell navigation mesh painted for that layer.

Instead of enabling the TileMap navigation the better option is to disable the TileMap (still paint your cell navigation mesh) and use a NavigationRegion2D as it adds agent_radius margin. The TileMap can not add such a margin and will get all your agents stuck on collision.

1 Like

Thank you very much, I’ll try it this way too.