May 25, 2010 at 22:55
I recently shared a simple PHP and jQuery animated pathfinding tech-demo through my Twitter account and promised to share the simple pathfinding class used for pathfinding calculations. The example shared in Twitter is still available here.
This example has a few limits, that is you can easily confuse it by clicking on two tile locations in a row. But in general it works and what I will be using this for will be something a bit different, so this limitation was of no concern to me. However the entire pathfinding calculation takes place on PHP backend. Each map is essentially a square (currently a limitation of pathfinder, but can easily be tweaked) and stored as an associative array, every tile in that array like this:
The first key is the coordinate of the single map tile and the weight key is used to store weight of this map tile for calculations. Nothing else is needed (and an example is provided in the files below). For actual game purposes or whatnot you can store additional information on that very map as long as the coordinate and weight are assigned as shown in the example. For example, in my own tech-demo I also store the graphic tile used in the map array.
Finding the actual path is just as simple:
$path=new PathFinder(); //Create new pathfinder object
$path->setOrigin(1,1); //Set the start location
$path->setDestination(20,20); //Set the destination
$path->setMap($map); //Assign the map to use for calculations
$result=$path->returnPath(); //Returns an array of all the walked steps
Working example, as well as commented pathfinder class is available below:
Please note that this is not a definitive pathfinder. It only takes into account one square ahead and on very large maps I am sure there are more ideal solutions. But for your basic browser based game this is a good starting point and I learned a lot by creating it. This is also easy to expand based on your needs.
If you have any other questions, let me know.
The code is shared entirely free for personal or commercial use.
Tags: open source, tutorial