---
title: "Deterministic crowd navigation in C#"
url: https://recursiveai.org/onegame/cookbook/steer-navigation-crowd/
description: "Move a crowd on a fixed map in C# with onegame. Send destinations through commands, step the world, and restore and replay crowd state."
version: "2.0.0"
---

# Deterministic crowd navigation in C#

**onegame** is a free, open-source game engine for .NET from Recursive AI. MIT or Apache-2.0, no editor required.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneGame.Navigation) · [GitHub](https://github.com/recursive-ai-oss/onegame) · [Docs](https://recursiveai.org/onegame/docs/) · [Download example (.zip)](https://recursiveai.org/onegame/cookbook/steer-navigation-crowd/steer-navigation-crowd.zip)

Move units with avoidance on a static map, using one unit size class.

```shell
dotnet add package RecursiveAI.OneGame.Navigation
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneGame.Core;
using OneGame.Navigation;
var world = new World(1,
    new EntityRegistry());
var space = new NavSpace(new FVec2(0, 0),
    Fixed.FromInt(16));
var map = NavGrid.FromText(
    "........\n........", space);
var crowd = NavCrowd.AddTo(world, map);
if (!crowd.TryAdd(new FVec2(8, 8), out var id))
    throw new Exception("Cannot spawn.");
crowd.SetDestination(id, new FVec2(104, 8));
for (var t = 0; t < 120; t++) world.Step();
var x = crowd.Agents[0].Position.X;
Console.WriteLine($"x={x}");
```

```text
x=93.97894761
```

Unzip [the example](https://recursiveai.org/onegame/cookbook/steer-navigation-crowd/steer-navigation-crowd.zip), then `dotnet run`.

## The full program

The snippet at the top initializes an authority world directly. In a game, register the map in `RegisterSystems` on every node and make changes through commands. This program adds two units, walks them for 120 ticks, restores a snapshot, then replays the recorded session.

The full program also uses the host package:

```shell
dotnet add package RecursiveAI.OneGame.Host
```

```csharp
using OneGame.Core;
using OneGame.Host;
using OneGame.Navigation;
using OneGame.UI;

using var game = GameInstance.Create(new CrowdGame(),
    new GameOptions { Headless = true });
var recording = game.StartSessionRecording();
var director = (Director)game.World.Entities[0];
director.Send.Cross();
game.Step(120);
foreach (var unit in NavCrowd.Of(game.World)!.Agents)
    Console.WriteLine($"Unit {unit.Id}: x={unit.Position.X}, y={unit.Position.Y}");
var hash = game.World.ComputeHash();
var snapshot = game.SaveSnapshot();
game.Step(1);
game.LoadSnapshot(snapshot);
Console.WriteLine($"Save hash matched: {hash == game.World.ComputeHash()}");
var session = recording.Stop();
Console.WriteLine($"Replay matched: {game.Replay(session).Ok}");

[Entity]
public partial class Director : Entity
{
    [Command]
    public void Cross()
    {
        var crowd = NavCrowd.Of(World!)!;
        for (var row = 0; row < 2; row++)
        {
            if (!crowd.TryAdd(new FVec2(8, 8 + row * 16), out var id))
                throw new InvalidOperationException("No walkable spawn or crowd full.");
            crowd.SetDestination(id, new FVec2(104, 8 + row * 16));
        }
    }
}

public sealed class CrowdGame : GameDefinition
{
    public override string Name => "crowd";
    public override void RegisterEntities(EntityRegistry registry) =>
        OneGame.Generated.CrowdRecipe.EntityTypes.Register(registry);
    public override void RegisterSystems(World world)
    {
        var map = NavGrid.FromText("........\n........\n........",
            new NavSpace(new FVec2(0, 0), Fixed.FromInt(16)));
        NavCrowd.AddTo(world, map, new NavCrowdOptions
        {
            AgentRadius = Fixed.FromInt(2), MaxAgents = 8
        });
    }
    public override void Setup(World world) => world.Add(new Director());
    public override void DefineScreens(ScreenSet screens) =>
        screens.Add("main", _ => Ui.Column());
}
```

```text
Unit 0: x=94.691647234, y=8.987611356
Unit 1: x=94.691647234, y=23.012388644
Save hash matched: True
Replay matched: True
```

`TryAdd` returns false when the crowd is full or no walkable ground exists; out-of-range fixed-point coordinates throw `NavRangeException`.

## Variations

Stop a unit after the loop in the snippet at the top:

```csharp
// crowd, id and world are from the snippet at the top.
crowd.Stop(id);
world.Step();
Console.WriteLine(crowd.Agents[0].Status);
```

```text
Idle
```

In a networked game, put that change in a command handler too.

## Related recipes

- [Find a path on a grid](https://recursiveai.org/onegame/cookbook/pathfinding/)
- [Record and replay a game](https://recursiveai.org/onegame/cookbook/record-and-replay/)

## The short answer

Use `NavCrowd.AddTo` to attach a crowd to a onegame world, then add units with `TryAdd` and send them toward goals with `SetDestination`. The registered system advances them once per world tick. You don’t need a separate movement loop for each unit.

A crowd is different from a single path search: it includes local avoidance between moving units. The example starts on an open map so you can see the registration, command and state handling without extra level data. For walls, replace dots in the text map with `#`. Both the map and the registration options must be identical on every node.

## How do I build a deterministic crowd navigation example in C#?

Keep level construction separate from commands. The map belongs in `RegisterSystems`, which runs when the world is created, including when a saved world is rebuilt. The example’s `Director.Cross` command adds the units and sets their destinations. Commands run before the crowd’s tick, so the units begin moving in that tick. Calling these mutating methods on a replica throws `ReplicaWriteException`.

The positions exposed to simulation code are `FVec2` values with `Fixed` components. Underneath, OnePath holds crowd positions as doubles within ±2²¹ world units. The wrapper’s conversion to fixed point scales by 2³² and rounds to nearest, ties to even. Conversion in the other direction is checked and exact in the supported range. These are the rules in the [navigation guide](https://recursiveai.org/onegame/docs/navigation/), not a claim that arbitrary floating-point game code becomes deterministic.

The crowd’s world table contains positions, velocities, destinations, path corridors, avoidance memory, unit numbers and the step counter. Snapshots, saves, session replay and the world hash include that table. The full program compares the hash before and after restore and checks the recorded replay. Those checks cover this example’s starting state and commands; your own command sequence still needs testing.

After a restore, look up state from the current world again rather than keeping an old crowd or entity reference. The game rebuilds the world when loading a snapshot. `NavCrowd.Of(game.World)` retrieves the current table.

## What algorithm does deterministic crowd navigation use?

The wrapper uses OnePath’s crowd on a navigation mesh constructed from the grid’s walls. It handles path corridors and avoidance rather than simply following independent grid paths. `AgentRadius` shrinks the mesh when the crowd is built; a unit can have a smaller avoidance radius, but there is only one mesh size class per crowd.

Choose the map and radius before play begins. Editing the grid afterward does not update the crowd’s mesh. Runtime mesh editing, off-mesh links and per-unit filters are not wrapped. If a door must change the walkable mesh during play, this wrapper does not supply that operation.

Crowd state also has a networking consequence: replicas receive the whole table in a frame where it changes, not row-level deltas for individual units. A continuously walking crowd changes each tick. For a server-only crowd whose positions reach clients another way, the documented `Visibility.Hidden` setting keeps the table on the authority. That is a replication choice, not a different navigation algorithm.
