qiao / PathFinding.js

A comprehensive path-finding library for grid based games
http://qiao.github.io/PathFinding.js/visual/
8.41k stars 1.31k forks source link

get the shortest path in a for loop #142

Open hardyanto opened 7 years ago

hardyanto commented 7 years ago

I can get the shortest path for the first loop but Why can't I get the shortest path in the subsequent loop? Here are the codes:

var grid = new PF.Grid(numCols, numRows);

var gridBackup = grid.clone();
fnSetObstacles(gridBackup);
var finder = new PF.AStarFinder();

for (var c = 0; c < boothDesignatedCoords.length; c += 2) { var pathToEachDesignatedCoords = finder.findPath(1, 1, boothDesignatedCoords[c], boothDesignatedCoords[c + 1], gridBackup);

}

I can get the shortest path in the subsequent loop if I re-initialise the gridBackup in the for loop. Something like this: for (var c = 0; c < boothDesignatedCoords.length; c += 2) { var gridBackup = grid.clone(); }

But the problem is I have to re assign the obstacles etc. Is there a way for me to get the shortest path in a for loop without re-initializing the gridBackup? Thanks!

mfandl commented 7 years ago

Set the obstacles first and then clone the grid.

hardyanto commented 7 years ago

But there will be a problem because the shortest path finding in the for loop cannot use the obstacles.

mfandl commented 7 years ago

then i dont understand. i thought that by setting obstacles you mean adding additional non-walkable cells to the grid

hardyanto commented 7 years ago

sorry for the confusion. I mean yes you are right. I mean I want it to use the obstacles as additional non-walkable cells

hardyanto commented 7 years ago

But how? LOL

mfandl commented 7 years ago

Wait, I think I get it now.

Would something like this work if you use the workingGrid in the for loop?

var gridWithObstacles = grid.clone();
var workingGrid;
fnSetObstacles(gridWithObstacles);

for(;;) {
  workingGrid = gridWithObstacles.clone();
  ...
}

Also, if grid is really just an empty grid and you do not need to reuse it, you do not need to clone it. The important thing is that you can not use the grid you clone from and clone the grid that already has set everything you need.

hardyanto commented 7 years ago

Thank you so much for helping me :)

hardyanto commented 7 years ago

it works