Vehicle Following the Path

In the last three posts, we explored the how A* works, then we put A-star into code, then we looked at different heuristics for A*. Now we will combine A* pathfinding with the path following steering behavior.

We have already done most of the work to do this. But we’ll do a quick review in case you missed those posts.

A* Pathfinding

In A* we take a grid of cells and find a path from start to finish. Each cell has an x,y for location, a parent for creating the path, and F, G, and H values for calculating the cost of the path. A* searches the grid, excluding cells that are blocked and finds the optimal path to the finish. When it is done, it creates an array containing the cells for the path. For more information on A*, you can learn the basics here, how to put it into code here, and different heuristics to calculate cost here.

Path Following Steering Behavior

The path following steering behavior takes an array of Vector2D‘s and seeks them in order. It calculates the distance between the vehicle and the next location. If it is within 10 pixels, it considers that “on” the goal and moves on to seeking the next one.

This creates one minor problem. A* returns an array of cells, but the path following steering behavior expects an array of Vector2Ds. To make them work together, we need to make one small change. After we get A-star’s path, we need to run this function:

public function convertToVector2D(path:Array):Array {

for(var i:int = 0; i < path.length; i++){

path[i] = new Vector2D(path[i].x,path[i].y);

}

return path;

}

This will convert the path from cells to Vector2Ds. Now we can create a Vehicle and have it follow the path.

var vehicle:Vehicle = new Vehicle();
addChild(vehicle);
//in an update function (possibly enterFrame)
//where path is the converted array.
vehicle.followPath(path);
vehicle.update();

That’s it Using the ideas we used in previous posts, we were able to get a vehicle to follow a path found by A*. Click here to see it in action. It’s the same A* finder as before, but with a vehicle follow path button to create a vehicle that will follow the path.