Kristo Vaher

inventas vitam iuvat excoluisse per artes

Skip to: Content | Sidebar | Footer

A simple PHP pathfinder class – as promised

25 May, 2010 (22:55) | Web Development | By: Kristo Vaher

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:

$map['1x1']['weight']=1.0;

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:

$map=getMap();
require(‘class.pathfinder.php’);
$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:

Download the class and example file here

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.

Cheers!

Comments

Pingback from Tweets that mention Kristo Vaher ยป As promised, here is a simple PHP pathfinder class – creating castles in the air, from air, by exertion of the imagination — Topsy.com
Time May 25, 2010 at 11:22 pm

[...] This post was mentioned on Twitter by Janne Siera, Kristo Vaher. Kristo Vaher said: As promised, the simple PHP tile-map pathfinder (useful for PBBG's) is now available through my blog: http://waher.net/archives/313 [...]

Write a comment