This is the first step of a tutorial series which will guide you through the creation of pathfinding algorithms.
Pathfinding is the “art” of finding the shortest route between two points, and you can use it in several situations, such as when moving non-playing characters or when moving player controlled charachter if you use a “click to set destination” way to control it.
Before we start, let me clarify one thing: pathfinding works when the destination point is known. Also, being this just the first of a series of tutorials, I am going to show you a very basic and unefficent algorithm (but all in all, it works!), which will be improved and optimized until we’ll make the famous A* algorithm (and beyond!) in a very intuitive way.
I don’t want to publish “just another A* algorithm”, so following this series you will master the art of pathfinding rather than just copying some code. That’s why I built an animated example.
So, let’s examine the basics of this simple pathfinding algorithm:
* Given a start tile and a known end tile, I examine all tiles adjacent to start tile (no diagonals at the moment) which aren’t part of the path yet, and for each one I determine three values:
G: the cost of moving from start tile to examined tile. At the moment, I always leave it to 1.
H: the presumable distance from the examined to the end tile. I say “presumable” because I can only suppose the distance from current to end tile, as it may vary due to walls or movement cost. The easiest way to calculate the presumable distance is the Manhattan distance, which I’ll use in this example. If you need more information about Manhattan distance, check the blog post the fastest way to find the distance between two points.
F: simply G+H
* Once I examined all adjacent tiles, I pick the one with the lowest F value and set it as visited
* I restart the process from scratch using the picked tile as start tile
After some steps, I can have one of these two situations:
* I found the end tile. Achievement unlocked.
* I don’t have legal moves. In this case I must backtrack until I found a legal move, and continue the process, or I will backtrack until start tile, meaning the end tile cannot be reached.
This first, unoptimized algorithm can be written in AS3 this way:
package {
import flash.display.Sprite;
import flash.geom.Point;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Main extends Sprite {
private var canvas:Sprite;
private var startPoint:Point;
private var endPoint:Point;
private var currPoint:Point;
private var tileVector:Vector.