Moving a Game Character Along the A* Path

Let’s dig deeper into the logic behind Example 8-18. To add a game character to the path, we will need to use the x and y coordinates returned in the result array from the astar.search() function. This function does not return the starting point of our path, so we must use the startNode object values for the first node. After that, we can use the nodes from the path to have our tank follow. There is a lot of new code for this example, so let’s take it in small pieces, starting with the variable we will need.

Game variables for tank movement and node changes

Here are the variables we’ll use for tank movement and node changes:

var currentNodeIndex=0;
var nextNode;
var currentNode;
var rowDelta=0;
var colDelta=0;
var tankX=0;
var tankY=0;
var angleInRadians=0;
var tankStarted=false;
var tankMoving=false;
var finishedPath=false;

Following are brief descriptions of what these variables do:

currentNodeIndex

This will hold the integer of the current node on the path. Because the result array does not contain the entire path, we will need to calculate the location to draw the tank on the starting node in a slightly different manner than when the tank is moving along the A* node path.

nextNode

Contains the object values for the next node that the tank is moving to.

currentNode

Contains the object values for the node the tank is moving from.

rowDelta

Calculated each time the tank changes nodes. This represents the pixel change on the y-axis for the moving tank. ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.