PathFinding.js icon indicating copy to clipboard operation
PathFinding.js copied to clipboard

Problems with reusing finder.findPath()?

Open SamMakesCode opened this issue 5 years ago • 2 comments

My usage: When findPath returns an empty array because the destination is impassable, I'm testing various surrounding nodes to see if I can reach them instead.

Using AStar algorithm, the first time I call this function I receive a list of nodes as expected.

On subsequent calls using the same instance of AStarFinder with the same grid but different coordinates, I seem to receive empty arrays in response.

SamMakesCode avatar Jan 13 '20 22:01 SamMakesCode

Just an update on what I've discovered here...

It seems as though AStarFinder.findPath() manipulates the PFGrid in some way.

If instead I do this:

finder.findPath(this.x, this.y, x, y, grid.clone());

I get the expected behaviour.

SamMakesCode avatar Jan 13 '20 22:01 SamMakesCode

Yes, the implementation in Pathfinding.js stores which nodes it has seen in the nodes themself, so the grid needs to be cloned before or reset afterwards (see for example the opened and closed variables in the finder). In theory this could be changed, the pseudo code at Wikipedia shows a version that stores everything in an own objects/arrays without modifying the grid. I think both versions have their benefits and drawbacks when it comes to execution time and memory usage. I think it should not make much of a difference, but it maybe makes sense to implement the pseudo code and run some benchmarks. For a possible speedup you could also think of storing some (sub-)paths and keep some of the information, but than it is not a general A* anymore.

brean avatar Jan 14 '20 10:01 brean