Search code examples
javascriptpath-finding

pathFinding.js library - only first path is correct


I'm using PathFinding.js package. My code is:

var grid = new PF.Grid(6, 6);
grid.setWalkableAt(0, 1, false);
grid.setWalkableAt(1, 1, false);
grid.setWalkableAt(2, 1, false);
grid.setWalkableAt(3, 1, false);
grid.setWalkableAt(4, 1, false);
grid.setWalkableAt(1, 2, false);
grid.setWalkableAt(0, 3, false);
grid.setWalkableAt(1, 3, false);
var finder = new PF.AStarFinder();
var path1 = finder.findPath(0, 0, 2, 2, grid);
var path2 = finder.findPath(0, 0, 0, 2, grid);
var path3 = finder.findPath(0, 0, 5, 0, grid);
console.log(path1.length)
console.log(path2.length)
console.log(path3.length)

codepen demo

and this is visualisation of above board:

alt

(but x and y are other way around, my mistake in the image)

I'm checking path length of all 3 green points to check which is shortest later. Unfortunately only first path has correct length. Why? am I not using correct package? I followed docs from link from 1st line of this question.


I don't think that's this is a package issue because it's widely used and has over 6k stars at GH.


Solution

  • I didn't noticed this sentence in docs:

    Be aware that grid will be modified in each path-finding, and will not be usable afterwards. If you want to use a single grid multiple times, create a clone for it before calling findPath.

    So I have to create grid clone. Later I'll use finder in loop so within it I need to reassign grid clone each time in loop:

    gridBackup = grid.clone();