Skip to content

Pathfinding

shmellyorc edited this page Sep 13, 2026 · 6 revisions

Pathfinding

VOID's AStar2D stores a 2D navigation graph and can search it with A*, Dijkstra, BFS, or Greedy Best-First.

It also supports weighted points, directed connections, diagonal rules, partial paths, custom cost/heuristic callbacks, neighbor filtering, and flow fields.

Creating a Pathfinder

using var pathfinder = new AStar2D(initialCapacity: 1000);

Capacity grows automatically when needed. Reserving enough space up front avoids some array resizing.

Adding Points

pathfinder.AddPoint(0, new Vect2(0, 0));
pathfinder.AddPoint(1, new Vect2(10, 0));
pathfinder.AddPoint(2, new Vect2(10, 10));
pathfinder.AddPoint(3, new Vect2(0, 10));

Each point has:

  • a non-negative integer ID
  • a position
  • a weight scale
  • an enabled/disabled state

The built-in movement cost is the Euclidean distance between connected points multiplied by the destination point's weight scale.

pathfinder.SetPointWeightScale(2, 3f);
pathfinder.SetPointDisabled(3, true);

Node IDs from Tile Positions

For a tile map, MapHelper.To1D is convenient for stable IDs:

for (int y = 0; y < mapHeight; y++)
{
    for (int x = 0; x < mapWidth; x++)
    {
        var tile = new Vect2(x, y);
        int id = MapHelper.To1D(tile, mapWidth);

        pathfinder.AddPoint(
            id,
            MapHelper.MapToWorld(tile, tileSize));
    }
}

See MapHelper for map/world conversion helpers.

Connecting Points

Connections are bidirectional by default:

pathfinder.ConnectPoints(0, 1);
pathfinder.ConnectPoints(1, 2);

Create a directed connection:

pathfinder.ConnectPoints(
    2,
    3,
    bidirectional: false);

Disconnect points:

pathfinder.DisconnectPoints(0, 1);

Check a connection:

bool connected =
    pathfinder.ArePointsConnected(0, 1);

Finding Paths

IDs

Use GetIdPath when you want graph IDs:

List<int> path =
    pathfinder.GetIdPath(0, 2);

The result contains the start and final point IDs.

Positions

Use GetPointPath or GetPath when you want stored positions:

List<Vect2> path =
    pathfinder.GetPointPath(0, 2);

// GetPath is the position-returning convenience form.
List<Vect2> same =
    pathfinder.GetPath(0, 2);

An impossible path returns an empty list.

Partial Paths

If the target cannot be reached, VOID can return a path to the reachable point judged closest to the target:

List<int> partial =
    pathfinder.GetIdPath(
        startId,
        targetId,
        allowPartialPath: true);

Algorithms

The default algorithm is A*.

pathfinder.DefaultAlgorithm =
    PathAlgorithm.AStar;

Available algorithms:

Algorithm Behavior
AStar Accumulated path cost plus heuristic
Dijkstra Accumulated path cost only
BFS Edge count; ignores edge weights
GreedyBestFirst Heuristic only; fast but not guaranteed optimal

Override it for one query:

var path = pathfinder.GetIdPath(
    startId,
    targetId,
    algorithm: PathAlgorithm.Dijkstra);

Heuristics

The default heuristic is Heuristic.Octile.

pathfinder.DefaultHeuristic =
    Heuristic.Octile;

Available heuristics:

  • None
  • Manhattan
  • Euclidean
  • Octile
  • Chebyshev

Override it per query:

var path = pathfinder.GetIdPath(
    startId,
    targetId,
    heuristic: Heuristic.Manhattan);

Diagonal Movement

The default mode is DiagonalMode.Always.

pathfinder.DefaultDiagonalMode =
    DiagonalMode.AtLeastOneWalkable;

Modes:

Mode Behavior
Always Allows geometrically diagonal connections
Never Rejects connections whose endpoints differ on both axes
AtLeastOneWalkable Requires at least one adjacent corner point to exist and be enabled
OnlyIfNoObstacles Requires both adjacent corner points to exist and be enabled

The corner-checking modes are intended for grid-like graphs where those axis-aligned corner points exist.

Custom Costs

Callbacks receive point IDs, not positions.

Custom movement cost:

pathfinder.ComputeCostOverride = (fromId, toId) =>
{
    Vect2 from = pathfinder.GetPointPosition(fromId);
    Vect2 to = pathfinder.GetPointPosition(toId);

    float distance = Vect2.Distance(from, to);
    float terrain = GetTerrainCost(toId);

    return distance * terrain;
};

Custom heuristic:

pathfinder.EstimateCostOverride = (fromId, targetId) =>
{
    return Vect2.Distance(
        pathfinder.GetPointPosition(fromId),
        pathfinder.GetPointPosition(targetId));
};

Pathfinding expects custom movement costs to be finite and non-negative.

Neighbor Filtering

Enable the filter, then return true for an outgoing connection that should be rejected:

pathfinder.NeighborFilterEnabled = true;

pathfinder.FilterNeighborOverride =
    (fromId, toId) =>
        IsTemporarilyBlocked(fromId, toId);

The callback is ignored while NeighborFilterEnabled is false.

Flow Fields

A flow field precomputes the next step toward one target. It is useful when many units share the same destination.

FlowField field =
    pathfinder.ComputeFlowField(targetId);

Use the next node:

int next =
    field.GetNextNode(currentNodeId);

Or use a normalized direction:

Vect2 direction =
    field.GetDirection(currentNodeId);

Check whether an entry exists:

if (field.HasNode(currentNodeId))
{
    unit.MoveInDirection(
        field.GetDirection(currentNodeId));
}

Flow fields respect directed connections, disabled points, DefaultDiagonalMode, custom movement costs, and the enabled neighbor filter at the time they are computed. Recompute the field after changing graph state that affects traversal.

Useful Graph Queries

int count = pathfinder.PointCount;
int capacity = pathfinder.PointCapacity;

List<int> ids = pathfinder.GetPointIds();

int freeId = pathfinder.GetAvailablePointId();
int nearest = pathfinder.GetClosestPoint(worldPosition);

Vect2 nearestOnConnection =
    pathfinder.GetClosestPositionInSegment(worldPosition);

Reusing a Pathfinder

Clear() removes all points and connections while retaining allocated capacity:

pathfinder.Clear();

This is useful when rebuilding a graph without reallocating all backing storage.


Back to Home

Clone this wiki locally