Creating a modular game in JavaScript, part 2: Implementing Pathfinding

Last week I wrote about writing a pathfinding algorithm in javascript, so now we’ll be implementing it into our game. See part 1 of this series here.

This is the result of today’s implementation of pathfinding.

Since we’re using pathfinding now, the collision code is only going to get in the way, so we’ll get rid of the collision call in the draw function of the skeleton object:

The skeleton needs to be initialized with a few more attributes now since we need to know the goal target and the path target. The skeleton will be walking along a path to reach the mouse, so it needs to walk towards the next step of the path.

In updateVectors we’ll add calculations for the path vector

For an A* algorithm, for each node that it checks for a path you need a gCost which is the cost of the path so far, and an hCost, which is the estimated remaining path (ignoring walls).

decPlace is just a variable for keeping precision in rounding consistent. To see which node should be priority for checking for a new path, we add the g and h costs. This is called the fCost.

Each skeleton needs to make changes to its own grid so unfortunately we have to make the grid inside the skeleton object or else they would interfere with other skeletons’ paths.

Finally, the findPath function. First we’ll initialize a few key values we need to run the algorithm:

While the open set isn’t empty, first remove the current node from the open set and add it to closed. Check if the current node is the end node and if it is, return the path by pushing each node’s parent into an array in order. If it isn’t, get the neighboring nodes:

Iterate through the neighbors and check if they should be added to open. If it’s a wall, closed or around a corner, don’t add it. If it’s a valid node, add it to open and calculate it’s costs:

Finish the while loop by sorting an array of remaining open nodes and making the current node the one with the lowest estimated cost. If the loop checks every node, don’t move the skeleton and only return the goal node as the path.

Finally rewrite the draw function to get the path first:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store