Recursive AI

Constrain movement to a navmesh in C#

OnePath is a free, open-source pathfinding library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

When a character’s next step would leave the walkable floor, a navmesh can keep it on the surface and let it slide along the edge.

Terminal
dotnet add package RecursiveAI.OnePath

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OnePath;
using RecursiveAI.OnePath.Mesh;
using RecursiveAI.OnePath.Mesh.Queries;
 
bool[] floor = [true, true];
var settings = new NavSettings {
    TileSize = 4, AgentRadius = 0
};
// Walkable cells, width, height, cell size,
// map origin, and build settings.
var mesh = NavMesh.Build2D(floor, 2, 1,
    4, new(0, 0), settings);
var query = new NavMeshQuery(mesh.Tiles);
var start = query.FindNearestPoly(
    new(1, 0, 1), new(1, 1, 1));
Span<PolyRef> visited = stackalloc PolyRef[8];
var move = query.MoveAlongSurface(start.Poly,
    start.Point, new(10, 0, 3), null,
    visited, out int count);
if (move.Status != RaycastStatus.Ok)
    throw new InvalidOperationException(
        move.Status.ToString());
Console.WriteLine(
    $"{move.Position}; blocked: {move.Blocked}");
foreach (var poly in visited[..count])
    Console.WriteLine(poly);

The request ends outside the floor at (10, 0, 3), but the move stops at (8, 0, 3) after visiting two polygons.

Unzip the example, then dotnet run.

Text
(8, 0, 3); blocked: True
poly(salt 1, tile 0, poly 0)
poly(salt 1, tile 1, poly 0)

The full program

The sample floor is eight units wide and four deep. The program prints each polygon in visit order, then reports whether the list was truncated and which polygon owns the final position. The salt is a generation number that helps detect stale tile references.

C#
using RecursiveAI.OnePath;
using RecursiveAI.OnePath.Mesh;
using RecursiveAI.OnePath.Mesh.Queries;
 
bool[] floor = [true, true];
var settings = new NavSettings {
    TileSize = 4, AgentRadius = 0
};
// Walkable cells, width, height, cell size,
// map origin, and build settings.
var mesh = NavMesh.Build2D(floor, 2, 1,
    4, new(0, 0), settings);
var query = new NavMeshQuery(mesh.Tiles);
var start = query.FindNearestPoly(
    new(1, 0, 1), new(1, 1, 1));
Span<PolyRef> visited = stackalloc PolyRef[8];
var move = query.MoveAlongSurface(start.Poly,
    start.Point, new(10, 0, 3), null,
    visited, out int count);
if (move.Status != RaycastStatus.Ok)
    throw new InvalidOperationException(
        move.Status.ToString());
Console.WriteLine(
    $"{move.Position}; blocked: {move.Blocked}");
foreach (var poly in visited[..count])
    Console.WriteLine(poly);
 
Console.WriteLine($"Visit list truncated: {move.Truncated}");
Console.WriteLine($"Ending polygon: {move.Poly}");

dotnet run prints:

Text
(8, 0, 3); blocked: True
poly(salt 1, tile 0, poly 0)
poly(salt 1, tile 1, poly 0)
Visit list truncated: False
Ending polygon: poly(salt 1, tile 1, poly 0)

If the start reference is invalid or the start point is outside its polygon, Status is not Ok; don’t apply that result as a successful move.

Variations

To see an unobstructed step, replace the movement call with one whose endpoint is inside the same floor. The final position is the requested X/Z point, and Blocked is False.

C#
var move = query.MoveAlongSurface(start.Poly,
    start.Point, new(7, 0, 3), null,
    visited, out int count);
Text
(7, 0, 3); blocked: False
poly(salt 1, tile 0, poly 0)
poly(salt 1, tile 1, poly 0)
Visit list truncated: False
Ending polygon: poly(salt 1, tile 1, poly 0)

The short answer

Use NavMeshQuery.MoveAlongSurface with the current polygon, the current point on the floor and the requested endpoint. If Status is Ok, apply Position rather than the requested endpoint. The returned Poly owns that position, so use the pair as the next step’s starting point while that polygon reference remains valid. Blocked tells you a wall stopped the direct move; it doesn’t mean the move failed.

How do you keep a character on the navmesh?

Snap the initial position with FindNearestPoly, using search extents that match how far you are willing to move it in each direction. Use both the returned Poly and its Point: the original position may be outside the polygon even when the query finds a nearby surface. If there is no polygon within the search area, there is nowhere to start that move. In the example, the start is already inside the first tile, and the mesh has radius zero to make the boundary easy to see. For a character with width, build the 2D mesh with clearance for its radius so the mesh constrains the center of the character.

The movement traces the requested segment in X/Z. If it reaches the requested X/Z without hitting a wall, OnePath supplies the height of the finishing surface rather than keeping the requested Y. The visited buffer receives the polygon references in traversal order, starting with the initial polygon. Read only the first count entries. If Truncated is set, the list is incomplete even though the returned position and ending polygon are still usable. Check that flag if you use the visit list to keep other state in sync with the move.

What’s the difference between a navmesh raycast and moving along the surface?

A navmesh raycast tells you whether the straight segment hits a wall. MoveAlongSurface traces that same segment, but returns a position you can apply. On a hit it projects the requested endpoint onto the edge of the wall it hit. That can move the character along the wall past the original contact point. In the sample, the direct segment meets X = 8 before Z reaches 3, but the final point is (8, 0, 3). If the projection falls past an end of the edge, it clamps to the edge’s endpoint.

One call does one slide. It does not plan a detour around an obstacle or follow an off-mesh link such as a jump. Call it again from the returned point and polygon for the next local move; use a route query if the character needs to plan a way around the wall. The movement and raycast reference describes both queries.

All onepath recipes