In a tower defense game 200 enemies walk towards the same goal. With A* from Pathfinding on a Grid you run one search per enemy, each time from wherever it stands. If the player builds a tower in the middle of the road, all 200 routes are wrong and it starts over. You can also turn the search around: calculate once from the goal, and after that no enemy needs a search of its own.
The grid is 48 by 16 cells with a few walls and a cup right in front of the goal that opens towards the enemies. The orange dot is the goal, the 200 white squares are the agents. The color shows how many steps each cell is from the goal, the arrows point downhill. A click or drag moves the goal, chip 2 paints walls and you erase them by starting on a wall. Chip 6 lets every agent search with A* on its own. The card below the grid counts how many cells the search touched after the last change.
One search from the goal
A breadth first search that starts at the goal. The goal gets distance 0, its neighbors 1, their neighbors 2, and so on until all reachable ground is labeled:
std::vector<Cell> queue;
queue.reserve(f.dist.size());
queue.push_back(goal);
f.dist[g.index(goal.x, goal.y)] = 0;
for (std::size_t head = 0; head < queue.size(); ++head) {
const Cell c = queue[head];
const int d = f.dist[g.index(c.x, c.y)];
++f.expanded;
f.maxDist = std::max(f.maxDist, d);
for (const Cell n : kNeighbors) {
const int nx = c.x + n.x;
const int ny = c.y + n.y;
if (g.blocked(nx, ny) || f.dist[g.index(nx, ny)] != kUnreached) continue;
f.dist[g.index(nx, ny)] = d + 1;
queue.push_back({nx, ny});
}
}
expanded counts how many cells came out of the queue. On the start map that is 725, the number of reachable cells. The wave that grows from the goal after a click is only a drawing. The search is long finished and the agents use the finished field right away.
The arrows
Now every cell holds a number. The enemy should walk where the number gets smaller, so against the gradient. For each axis I take the two neighbors and subtract them:
const auto value = [&](int nx, int ny) {
const int d = f.at(nx, ny);
return g.blocked(nx, ny) || d == kUnreached ? c + 1 : d;
};
const double gx = static_cast<double>(value(x - 1, y) - value(x + 1, y));
const double gy = static_cast<double>(value(x, y - 1) - value(x, y + 1));
const double len = std::hypot(gx, gy);
if (len > 1e-9) return {gx / len, gy / len};
If the left neighbor is higher than the right one, gx comes out positive and the arrow points right. With a wall or the border as a neighbor the number is missing. I put in c + 1, so a wall counts as a slope going up. There is a reason: neighboring cells differ by 1 at most, so the opposite side is never larger than c + 1. On no axis does the arrow point into a wall. Only diagonally it can graze a corner, and pushOutOfWalls takes care of that by pushing the agent out of the wall.
Then there are cells where the gradient cancels out. In the test that is a ring around a block of wall with the goal at the top middle. The cell at the bottom middle has distance 5 on both its left and its right, a wall above and the border below. Both routes are equally long, gx and gy are 0. With no way out the agent would stand there forever. So in that case I take the first lower neighbor:
int best = c;
Vec2 dir{0.0, 0.0};
for (const Cell n : kNeighbors) {
const int d = value(x + n.x, y + n.y);
if (d < best) {
best = d;
dir = {static_cast<double>(n.x), static_cast<double>(n.y)};
}
}
return dir;
The agent
The agent does nothing anymore, it looks things up. buildDirections calculates all arrows once after every search, and in main.cpp the whole pathfinding part of an agent looks like this:
const ff::Vec2 d = app.dirs[app.grid.index(c.x, c.y)]; // the whole "search" of this agent: one lookup a.pos.x += d.x * step; a.pos.y += d.y * step;
The goal counts as reached as soon as the agent is inside the goal cell. My first attempt was a distance of 0.6 cells to the center, but the arrow in the goal cell itself is zero. The agents stopped at the edge of the cell, and the test that sends them to the goal from over a hundred start cells went red.
What it costs
The card below the grid shows it. The breadth first search costs 725 cells, once, no matter how many agents there are. After that every agent costs one array access per frame. With A* per agent it depends on where the agent stands. I measured it over all 725 cells of the start map with the demo's goal: 143 touched cells per search on average, the shortest 1, the longest 406. The cup in front of the goal lures A* in because the straight line leads there, and the search has to finish the cup before it goes around. With 200 agents the demo shows 29,508 at the start, a good 40 times the breadth first search. The number depends on where the agents stand right now, in my runs it was between 16,000 and 37,000.
For a single agent A* is clearly cheaper with 143 against 725. The flow field pays off from about five agents on this map (725 divided by 143). On open ground without walls the same grid averages only 25 touched cells per A* search against 768 for the breadth first search, and the sum only tips at about 30 agents.
Painting walls shows the second half. Every change knocks over the route of all agents. The flow field recalculates once, A* in the demo 200 times.
Pitfalls
Searching from the wrong end is the classic. The distance has to run to the goal, not to the agent, or it only holds for one agent. Then rebuild the field after every change of walls or goal, or everybody walks into a wall that is no longer there. And the walls themselves: arrows alone are not enough. An agent is no point in the middle of a cell, it has a radius and sticks into walls at corners, so it needs the collision.
The breadth first search only knows equal cost per step. If swamp should cost more than meadow it becomes Dijkstra, and the principle stays the same. The agents in the demo do not dodge each other, which is why they stream through the narrow spots as a dense chain. Red Blob Games explains the whole method in detail, Flow Field Pathfinding for Tower Defense and the 2024 article.
The code is in the repo under flow-field. The project Game Dev Snippets collects all demos of the series.