# Javascript A* path finding

I am trying to learn A* path finding. I am using this library - https://github.com/qiao/PathFinding.js

But there is one thing I don't understand how to do.

To find a path from player.x/player.y (player.x and player.y are both 0) to 10/10 I use this code

var path = finder.findPath(player.x, player.y, 10, 10, grid);


This gives an array of where I need to move, but how do I apply this array to my player.x and player.y?

The path structure looks like this

path = [[0, 0], [1, 0], [1, 1], ..., [10, 10]]


Try to use a timer to make changes to your player object. For example:

function makeMove() {
var nextPath = path.pop();
player.x = nextPath[ 0 ];
player.y = nextPath[ 1 ];
// draw your player object here
}

setInterval( makeMove, 1000 );


There are two ways you can use the information, the simplest to work with is to simply grab the next step, then throw away the path. This has the obvious downside that you waste a lot of resources by calculating the path the next frame again when you already knew:

var path = finder.findPath(player.x, player.y, 10, 10, grid)
player.x = path[1][0]
player.y = path[1][1]
path = null


The second, better option, is to store the path with the player

if (!player.path)
{
var path = finder.findPath(player.x, player.y, 10, 10, grid)
path.reverse() // To put the first steps last in the array so we can use pop
path.pop() // The first point in the array is the starting position
player.path = path
}
var step = player.path.pop()
if (step)
{
player.x = step[0]
player.y = step[1]
}


This code will move along the path to the destination, one step each time its called, the first time it calculates the path and then it reuses the existing path until the destination has been reached. To change where the player is going simply set a new path, or clear the existing one.