Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to learn A* path finding. I am using this library -

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]]
share|improve this question

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 );
share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.