As a #gamedev, you might be familiar with pathfinding algorithms such as A* or Dijkstra.

But not many know how they actually work...

Pathfinding algorithms might be complex, but they're not complicated.

So let's find out how they actually work!

๐Ÿงต
When a problem is too complex to be tackled, it is not uncommon to start with a simpler one.

โ“ Is point B REACHABLE from point A?

That's easy to test! Starting from A, let's "expand"/"explore" to its surrounding nodes.

And repeat, until B is found or no new cell is found.
That is known as the FLOOD FILL algorithm.

And once implemented, it can be easily extended to answer a more difficult question.

โ“ What is the DISTANCE between A and B?

All you need is to count how many iterations you have done before reaching B!
We're almost there!

โ“ What is the PATH between A and B?

Instead of just counting how many steps we do, we can label each cell to remember where we came from!

This creates a MINIMUM SPANNING TREE!

Once B is reached, we follow the arrows in reverse and that is our path!
And that's it, really! โœจ

Virtually all pathfinding algorithms found in games work exactly like this!

In fact:

- Depth-First Search
- Breadth-First Search
- Dijkstra Algorithm
- A*

...are all "variants" of the same pathfinding algorithm: FRONTIER SEARCH!
Now, there's one small problem that we might need to address...

The order in which we explore the nodes is VERY important, as it can create a different SPANNING TREE!
Ultimately, this could lead to very different paths...

Regardless of the order in which you explore/expands your cells, you will EVENTUALLY find a path. But this does not guarantee it is the shortest one!
If you want to make sure you can ALWAYS get the SHORTEST path between two points, you need the following condition:

Before exploring a cell at distance N, make sure you have explored all other cells at distance N-1!

And this makes the pathfinding algorithm OPTIMAL!
โœจ ๐˜๐—ต๐—ฎ๐—ป๐—ธ ๐˜†๐—ผ๐˜‚ ๐—ณ๐—ผ๐—ฟ ๐—ฐ๐—ผ๐—บ๐—ถ๐—ป๐—ด ๐˜๐—ผ ๐—บ๐˜† ๐˜๐—ฒ๐—ฑ ๐˜๐—ฎ๐—น๐—ธ โœจ

If you enjoy content about gamedev, shader coding and artificial intelligence, feel free to retweet & follow me for more! ๐Ÿ˜Ž
You can follow @AlanZucconi.
Tip: mention @twtextapp on a Twitter thread with the keyword โ€œunrollโ€ to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.