Grid pathfinding with a lot of entities
- by Vee
I'd like to explain this problem with a screenshot from a released game, DROD: Gunthro's Epic Blunder, by Caravel Games.
The game is turn-based and tile-based.
I'm trying to create something very similar (a clone of the game), and I've got most of the fundamentals done, but I'm having trouble implementing pathfinding.
Look at the screenshot. The guys in yellow are friendly, and want to kill the roaches.
Every turn, every guy in yellow pathfinds to the closest roach, and every roach pathfinds to the closest guy in yellow.
By closest I mean the target with the shortest path, not a simple distance calculation.
All of this without any kind of slowdown when loading the level or when passing turns.
And all of the entities change position every turn. Also (not shown in screenshot), there can be doors that open and close and change the level's layout.
Impressive.
I've tried implementing pathfinding in my clone.
First attempt was making every roach find a path to a yellow guy every turn, using a breadth-first search algorithm. Obviously incredibly slow with more than a single roach, and would get exponentially slower with more than a single yellow guy.
Second attempt was mas making every yellow guy generate a pathmap (still breadth-first search) every time he moved. Worked perfectly with multiple roaches and a single yellow guy, but adding more yellow guys made the game slow and unplayable.
Last attempt was implementing JPS (jump point search). Every entity would individually calculate a path to its target. Fast, but with a limited number of entities. Having less than half the entities in the screenshot would make the game slow. And also, I had to get the "closest" enemy by calculating distance, not shortest path.
I've asked on the DROD forums how they did it, and a user replied that it was breadth-first search. The game is open source, and I took a look at the source code, but it's C++ (I'm using C#) and I found it confusing.
I don't know how to do it. Every approach I tried isn't good enough. And I believe that DROD generates global pathmaps, somehow, but I can't understand how every entity find the best individual path to other entities that move every turn.
What's the trick?
This is a reply I just got on the DROD forums:
Without having looked at the code I'd wager it's two (or so) pathmaps
for the whole room:
One to the nearest enemy, and one to the nearest friendly for every
tile.
There's no need to make a separate pathmap for every entity when the
overall goal is "move towards nearest enemy/friendly"... just mark
every tile with the number of moves it takes to the nearest target and
have the entity chose the move that takes it to the tile with the
lowest number.
To be honest, I don't understand it that well.