In this lesson, you’ll learn how to replace expensive individual pathfinding calculations with flow fields to guide large crowds using a unified vector map.
The Problem with Individual Pathfinding
When you have hundreds of units—like an RTS army or a zombie horde—calculating an A* path for every agent every few frames will quickly cripple your CPU. Even with the NavMesh optimizations we discussed earlier, individual pathfinding becomes redundant when all units share the same destination. Instead of asking every agent to calculate a path, we flip the logic: we calculate the path once for the entire map, and the agents simply "follow the current."
Understanding Flow Fields
A flow field is essentially a grid of vectors covering your game world. Each cell in this grid stores a single Vector3 representing the direction an agent should travel to reach the target.
To generate this:
- Dijkstra Map: Perform a single search from your destination tile outward to all other tiles, storing the "distance" from the goal in each cell.
- Vector Field: Calculate the gradient of those distances. The direction pointing from a cell with a high distance value to an adjacent cell with a lower distance value becomes the vector for that cell.
For your agents, movement becomes incredibly cheap. They don’t need to know the path; they only need to look up the vector in the grid cell they currently occupy:
// Simple agent steering logic
Vector3 currentFlow = flowField.GetVectorAtPosition(transform.position);
rb.velocity = currentFlow * moveSpeed;
Why This Scales
Because the flow field is a grid, the cost of pathfinding is decoupled from the number of agents. Whether you have 10 units or 1,000, the "map" is generated once per destination update. Agents become lightweight observers of the environment rather than complex pathfinding entities. This approach handles crowding naturally, as agents are simply pushed along the same stream, effectively avoiding the jittery path-recalculation issues often found in multi-agent NavMesh systems.
Key Takeaway: By pre-calculating a global vector map, you shift the computational burden from the agent to the environment, allowing your game to handle massive crowds with negligible per-unit performance costs.