TExcelTAD
Home › Game AI › Navigation Meshes

Navigation Meshes

Grids are great for tile games, but a 3D level with ramps, stairs, balconies and curved walls would need millions of tiny cells. A navigation mesh (navmesh) describes the walkable floor instead as a set of convex polygons. Convex matters: inside a convex polygon, any two points can be joined by a straight line that stays inside it, so an agent can move freely within a polygon and only needs a search to decide which polygons to cross. A big open courtyard becomes one polygon instead of thousands of cells.

Unity's AI Navigation package, Unreal Engine's navigation system and Godot's NavigationServer all use navmeshes. Unreal Engine and Godot bake theirs with Recast, the open-source navmesh generator by Mikko Mononen, and Unreal also queries the mesh with Recast's companion runtime library, Detour. Whatever the engine, the ideas below are the same.

How a navmesh is built

Recast's pipeline, which you'll see reflected in every engine's bake settings:

  1. Voxelize the level geometry into a 3D grid of small boxes.
  2. Keep the voxels an agent could stand on: slope below the max slope, enough head room above (agent height), steps below the step height.
  3. Erode the walkable area by the agent radius, so the centre of the agent can go anywhere on the mesh without its body clipping walls.
  4. Split the walkable area into regions, trace their outlines, and triangulate them into convex polygons.

Because of step 3, a navmesh is baked per agent size: a giant needs a different mesh from a rat. Engines let you define several agent types for that reason.

Searching a navmesh

Two polygons that share an edge are neighbours, and the shared edge is a portal the agent passes through. Here is a tiny navmesh: four rectangles (rectangles are convex) around a solid block in the middle. The agent starts at S in the left polygon and wants to reach G in the right one:

text
 y
 8 +-----------------------------+
   |            P3 (top)         |
 6 +==portal A==+-------+=portal B=+
   |  S         |#######|      G |
   |  P0        |#block#|   P2   |
 2 |  (left)    +-------+ (right)|
   |      portal C  P1  portal D |
 0 +------------+-------+--------+
   0            3       7       10  x

What is the cost of moving from one polygon to the next? A naive answer is "the distance between polygon centres". The program below tries that first, then the usual engine approach: search over the portal midpoints (plus the real start and goal points), which measures distances the agent would actually walk:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var polys = new (string name, double x0, double y0, double x1, double y1)[]
{
    ("P0 left", 0, 0, 3, 6), ("P1 bottom", 3, 0, 7, 2), ("P2 right", 7, 0, 10, 6), ("P3 top", 0, 6, 10, 8),
};
var start = (x: 1.0, y: 5.0);
var goal = (x: 9.0, y: 5.0);
double Dist((double x, double y) a, (double x, double y) b) => Math.Sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
(double x, double y) Centre(int i) => ((polys[i].x0 + polys[i].x1) / 2, (polys[i].y0 + polys[i].y1) / 2);

// Portals: the overlapping part of an edge two rectangles share.
var portals = new List<(int a, int b, (double x, double y) p, (double x, double y) q)>();
for (int i = 0; i < polys.Length; i++)
    for (int j = i + 1; j < polys.Length; j++)
    {
        var (A, B) = (polys[i], polys[j]);
        double lo, hi;
        if (A.x1 == B.x0 || A.x0 == B.x1)
        {
            double x = A.x1 == B.x0 ? A.x1 : A.x0;
            lo = Math.Max(A.y0, B.y0); hi = Math.Min(A.y1, B.y1);
            if (hi > lo) portals.Add((i, j, (x, lo), (x, hi)));
        }
        else if (A.y1 == B.y0 || A.y0 == B.y1)
        {
            double y = A.y1 == B.y0 ? A.y1 : A.y0;
            lo = Math.Max(A.x0, B.x0); hi = Math.Min(A.x1, B.x1);
            if (hi > lo) portals.Add((i, j, (lo, y), (hi, y)));
        }
    }
foreach (var pt in portals)
    Console.WriteLine(
quot;portal {polys[pt.a].name} | {polys[pt.b].name}: ({pt.p.x},{pt.p.y})-({pt.q.x},{pt.q.y})"); // 1) Search over polygon centres. var polyEdges = portals.SelectMany(pt => new[] { (pt.a, pt.b), (pt.b, pt.a) }).ToList(); var (cost1, route1) = Search(polys.Length, 0, 2, (u, v) => polyEdges.Contains((u, v)) ? Dist(Centre(u), Centre(v)) : -1); Console.WriteLine(
quot;centre graph: {string.Join(" -> ", route1.Select(i => polys[i].name))}, estimated {cost1:F2}"); // 2) Search over points: 0 = start, 1 = goal, 2.. = portal midpoints. Points in the same polygon are linked. var pts = new List<((double x, double y) at, int[] inPolys)> { (start, new[] { 0 }), (goal, new[] { 2 }) }; foreach (var pt in portals) pts.Add((((pt.p.x + pt.q.x) / 2, (pt.p.y + pt.q.y) / 2), new[] { pt.a, pt.b })); var (cost2, route2) = Search(pts.Count, 0, 1, (u, v) => pts[u].inPolys.Intersect(pts[v].inPolys).Any() ? Dist(pts[u].at, pts[v].at) : -1); Console.WriteLine(
quot;portal graph: {string.Join(" -> ", route2.Select(i =>
quot;({pts[i].at.x},{pts[i].at.y})"))}, length {cost2:F2}"); // Dijkstra over a small graph; edge(u, v) returns a cost, or -1 when there is no edge. (double, List<int>) Search(int n, int from, int to, Func<int, int, double> edge) { var g = Enumerable.Repeat(double.PositiveInfinity, n).ToArray(); var prev = new int[n]; var open = new PriorityQueue<int, (double f, int order)>(); int order = 0; g[from] = 0; open.Enqueue(from, (0, order++)); while (open.TryDequeue(out int u, out var pri)) { if (u == to) break; for (int v = 0; v < n; v++) { double c = v == u ? -1 : edge(u, v); if (c < 0 || g[u] + c >= g[v]) continue; g[v] = g[u] + c; prev[v] = u; open.Enqueue(v, (g[v], order++)); } } var route = new List<int> { to }; while (route[^1] != from) route.Add(prev[route[^1]]); route.Reverse(); return (g[to], route); }
portal P0 left | P1 bottom: (3,0)-(3,2)
portal P0 left | P3 top: (0,6)-(3,6)
portal P1 bottom | P2 right: (7,0)-(7,2)
portal P2 right | P3 top: (7,6)-(10,6)
centre graph:  P0 left -> P1 bottom -> P2 right, estimated 8.06
portal graph:  (1,5) -> (1.5,6) -> (8.5,6) -> (9,5), length 9.24

The centre graph picks the route under the block: measured centre to centre, the bottom polygon is a shortcut. But the agent stands near the top of the left polygon, and its goal is near the top of the right one, so going over the top is much shorter in reality. Polygons on a navmesh vary wildly in size, which makes centre-to-centre costs unreliable. Searching over portal edges (Detour uses edge midpoints as the positions of the search nodes) with the real start and goal points included gives the right corridor.

The funnel algorithm: from corridor to straight path

The search returns a corridor: a list of polygons and the portals between them. Walking from portal midpoint to midpoint would look as clumsy as an unsmoothed grid path. The funnel algorithm (the "simple stupid funnel" variant popularized by Mononen) pulls the string tight through the portals: it keeps a funnel from the current apex to the left and right ends of the portals, narrows it portal by portal, and when one side would cross the other, the corner it crossed becomes a new waypoint.

csharp · try it yourself
using System;
using System.Collections.Generic;

var start = (x: 1.0, y: 5.0);
var goal = (x: 9.0, y: 5.0);
// The corridor's portals as (left, right), seen from the direction of travel: up through portal A, down through B.
var portals = new List<((double x, double y) left, (double x, double y) right)>
{
    (start, start),
    ((0, 6), (3, 6)),
    ((10, 6), (7, 6)),
    (goal, goal),
};

// > 0 when c is to the left of the line a->b, < 0 to the right.
double Cross((double x, double y) a, (double x, double y) b, (double x, double y) c) =>
    (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);

var path = new List<(double x, double y)> { start };
var apex = start; var left = start; var right = start;
int apexIndex = 0, leftIndex = 0, rightIndex = 0;
for (int i = 1; i < portals.Count; i++)
{
    var (l, r) = portals[i];
    if (Cross(apex, right, r) >= 0)                       // r narrows the funnel on the right
    {
        if (apex == right || Cross(apex, left, r) < 0) { right = r; rightIndex = i; }
        else                                              // crossed the left side: its corner is a waypoint
        {
            path.Add(left); Console.WriteLine(
quot;portal {i}: right side crossed left, corner ({left.x},{left.y})"); apex = left; apexIndex = leftIndex; left = right = apex; leftIndex = rightIndex = apexIndex; i = apexIndex; continue; } } if (Cross(apex, left, l) <= 0) // l narrows the funnel on the left { if (apex == left || Cross(apex, right, l) > 0) { left = l; leftIndex = i; } else // crossed the right side: its corner is a waypoint { path.Add(right); Console.WriteLine(
quot;portal {i}: left side crossed right, corner ({right.x},{right.y})"); apex = right; apexIndex = rightIndex; left = right = apex; leftIndex = rightIndex = apexIndex; i = apexIndex; continue; } } } path.Add(goal); double length = 0; for (int i = 1; i < path.Count; i++) length += Math.Sqrt(Math.Pow(path[i].x - path[i - 1].x, 2) + Math.Pow(path[i].y - path[i - 1].y, 2)); Console.WriteLine("path: " + string.Join(" -> ", path.ConvertAll(p =>
quot;({p.x},{p.y})")) +
quot;, length {length:F2}");
portal 2: left side crossed right, corner (3,6)
portal 3: left side crossed right, corner (7,6)
path: (1,5) -> (3,6) -> (7,6) -> (9,5), length 8.47

The agent now walks from S straight to the corner of the block at (3,6), along its top edge, and down to G: exactly the path a person would take. In an engine the same thing happens in 3D, on triangles rather than rectangles, and the result is the list of "corners" an agent steers towards (Detour's findStraightPath, the path corners you see in Unity's and Godot's debug views).

Note: The corner points touch the block exactly. That's fine on a real navmesh because the mesh was already eroded by the agent radius at bake time: the polygon edge is one radius away from the actual wall.

What else a navmesh system gives you

Feature What it does
Off-mesh links connections that aren't floor: jumps, ladders, doors, teleporters; the agent plays a special animation to traverse them
Area types / costs tag polygons as water, road, or danger with cost multipliers, like the terrain costs in Dijkstra
Dynamic obstacles carve holes into the mesh at runtime (crates, closed doors), or rebuild small tiles of the mesh
Local avoidance agents steer around each other (Detour's crowd module, Unity's and Godot's RVO-style avoidance), see Obstacle Avoidance
Nearest-point queries snap a clicked position or a spawn point onto the mesh

The engine lessons show these in practice: Unity: AI Navigation & Behavior, Unreal: AIController, Behavior Trees & Blackboard and Godot: NavigationAgent3D.

Test yourself

Why must navmesh polygons be convex?

  1. Convex polygons render faster
  2. Any two points inside a convex polygon can be joined by a straight line inside it, so movement within a polygon needs no search
  3. Engines can't store concave polygons
  4. Convex polygons have fewer edges

Why is a navmesh baked separately for different agent sizes?

  1. Bigger agents walk faster
  2. The walkable area is eroded by the agent's radius (and filtered by its height), so each size gets a different mesh
  3. Each agent needs its own copy for threading
  4. It isn't; one mesh fits all

What does the funnel algorithm produce?

  1. The polygon corridor
  2. The straightest path through a corridor's portals, as a list of corner points
  3. A new navmesh
  4. The heuristic