NavigationAgent3D
Enemies that walk around walls, villagers that follow roads, units that go where you click: they all need pathfinding. Godot's navigation system has three parts:
| Part | Node or class | Job |
|---|---|---|
| Where you can walk | NavigationRegion3D with a NavigationMesh |
a set of convex polygons covering the walkable floor, baked from the level geometry |
| The world's navigation | NavigationServer3D and a navigation map |
merges all regions of a World3D and answers path queries |
| A walker | NavigationAgent3D (child of your character) |
asks for a path, tracks the next waypoint, optionally avoids other agents |
The agent never moves anything: it tells your CharacterBody3D where to go next, and your code sets velocity and calls move_and_slide(), exactly as for a player (CharacterBody3D & 3D Physics). 2D has the same set of classes with 2D in the name.
Baking a navigation mesh (editor)
- Add a
NavigationRegion3Dto your level and make the level geometry (floors, walls, static meshes) its children. - Select the region and, in the inspector, create a New NavigationMesh.
- Set the agent size the mesh is baked for:
agent_radius(default 0.5 m),agent_height(1.5 m),agent_max_climb(0.25 m) andagent_max_slope(45°). The baker shrinks the walkable area by the radius so agents don't scrape walls. - Click Bake NavigationMesh in the toolbar. The walkable area appears as a translucent blue overlay. Turn it on in a running game with Debug > Visible Navigation.
- Re-bake whenever the level changes. Use
parsed_geometry_typeto choose between mesh instances, static colliders or both.
Different agent sizes (a rat and a troll) need different navigation meshes on different maps or with different navigation layers.
Following a path
Enemy (CharacterBody3D) enemy.gd
├── CollisionShape3D
├── Model
└── NavigationAgent3D path_desired_distance 0.5, target_desired_distance 1.0extends CharacterBody3D
@export var speed := 4.0
@export var target: Node3D
@onready var agent: NavigationAgent3D = $NavigationAgent3D
func _ready() -> void:
# The navigation map is only synchronised after the first physics frame.
set_physics_process(false)
await get_tree().physics_frame
set_physics_process(true)
func _physics_process(delta: float) -> void:
agent.target_position = target.global_position # cheap: only re-paths when needed
if agent.is_navigation_finished():
velocity = Vector3.ZERO
return
var next := agent.get_next_path_position()
var dir := global_position.direction_to(next)
dir.y = 0.0
velocity = dir.normalized() * speed
move_and_slide()Key details:
- Wait one physics frame before the first query. In
_ready()the map has not been synchronised yet, and the path comes back empty. This is the most common "my agent doesn't move" bug. get_next_path_position()must be called every physics frame: it advances along the path as you get withinpath_desired_distanceof each point.is_navigation_finished()becomes true withintarget_desired_distanceof the target. Signalstarget_reached,navigation_finished,waypoint_reachedandpath_changedlet you react without polling.- Setting
target_positionevery frame is fine; the agent only requests a new path when the target moves enough or the agent strays off the path.
Avoidance: agents that don't bump into each other
Paths are computed against static geometry only. To keep a crowd from walking through each other, enable RVO avoidance: set avoidance_enabled = true and radius on the agent, then hand it the velocity you want and use the safe velocity it gives back:
func _ready() -> void:
agent.avoidance_enabled = true
agent.velocity_computed.connect(_on_velocity_computed)
func _physics_process(delta: float) -> void:
if agent.is_navigation_finished():
return
var dir := global_position.direction_to(agent.get_next_path_position())
agent.velocity = dir * speed # the velocity we would like
func _on_velocity_computed(safe_velocity: Vector3) -> void:
velocity = safe_velocity # adjusted to avoid nearby agents
move_and_slide()The result arrives through the velocity_computed signal in the same physics frame. Moving obstacles that are not agents (a rolling boulder) use a NavigationObstacle3D. Avoidance uses avoidance_layers and avoidance_mask, independent of collision layers.
Doors, bridges and costs
- Navigation layers (
navigation_layerson regions and agents) restrict who may use an area: layer 2 for "only flying units", for example. NavigationLink3Dconnects two places that the mesh doesn't join: a ladder, a jump, a teleporter.travel_costandenter_coston a region make agents prefer roads over swamps.- Changing the level at runtime: re-bake with
NavigationRegion3D.bake_navigation_mesh()(it can run on a thread), or toggle regions withenabled.
The algorithm underneath (runnable)
Under the hood, the navigation server runs an A* search over the mesh polygons and then straightens the corridor into a smooth path. Godot also exposes A* directly for grid and graph games, through AStarGrid2D and AStar3D. They are pure data structures, so this runs headless:
extends SceneTree
func _init():
# A 6x4 grid with a wall at x = 3, open only at the bottom row
var grid := AStarGrid2D.new()
grid.region = Rect2i(0, 0, 6, 4)
grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
grid.update()
for y in 3:
grid.set_point_solid(Vector2i(3, y))
var path := grid.get_id_path(Vector2i(0, 0), Vector2i(5, 0))
print(path.size() - 1, " steps: ", path)
# A graph: rooms connected by corridors; room 2 is a slow swamp
var a := AStar3D.new()
a.add_point(1, Vector3(0, 0, 0))
a.add_point(2, Vector3(5, 0, 0))
a.add_point(3, Vector3(5, 0, 5))
a.add_point(4, Vector3(0, 0, 5))
a.connect_points(1, 2)
a.connect_points(2, 3)
a.connect_points(1, 4)
a.connect_points(4, 3)
print("no cost: ", a.get_id_path(1, 3))
a.set_point_weight_scale(2, 3.0)
print("room 2 costs 3x: ", a.get_id_path(1, 3))
quit()11 steps: [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (3, 3), (4, 3), (4, 2), (4, 1), (4, 0), (5, 0)]
no cost: [1, 2, 3]
room 2 costs 3x: [1, 4, 3]
Both routes through the graph are 10 units long, so A* takes the first one it finds. Making room 2 three times as expensive to cross (a swamp) sends the path through room 4 instead: that is what travel_cost does for navigation regions. AStarGrid2D is often all a tile-based or tactics game needs; it pairs naturally with a TileMapLayer (local_to_map converts positions to cells). The Game AI course covers A*, heuristics and flow fields in depth.
Test yourself
An enemy calls agent.target_position = ... in _ready() and gets an empty path. What is the usual fix?
- Bake the navigation mesh at runtime
- Wait for the first physics frame (
await get_tree().physics_frame) before querying, because the map isn't synchronised yet - Use
_processinstead - Increase
agent_radius
With avoidance enabled, where should the character's final velocity come from?
- Directly from
get_next_path_position() - From the
safe_velocitypassed to thevelocity_computedsignal - From
NavigationServer3D.map_get_path - Avoidance moves the body itself
Does NavigationAgent3D move its parent body?
- Yes, it sets
positionitself - No; it only provides path positions (and safe velocities), and your script moves the body
- Only RigidBody3D parents
- Only in 2D