I have been making a top down shooter, and when I spawn multiple HostileEntity's(the super-class of any "enemy", that contains all of the pathfinding functions), the enemies either:
- Don't move from the start of the game
- Start moving once the game starts, but all freeze once I move the player.
In my Algorithm class it freezes at this function
public Path backtrackPath(Node fromNode) {
Path path = new Path();
while(fromNode.getPreviousNode() != null) {
path.prependWaypoint(fromNode);
fromNode = fromNode.getPreviousNode();
}
reset(); //Resets all of the previousNodes to null
//so the next iteration will(should) work correctly
return path;
}
In which fromNode is retrieved from method findPath, and is the "goal", the player's coordinates, of the pathfinding algorithm. The bug is that it goes from, say Node A, which has previousNode as Node B, while Node B has previousNode as Node A, so the while loop runs back and forth indefinitely.
A slice of findPath()
if(neighborIsBetter) { //if the next neighbor node is closer to the goal then current node being checked
neighbor.setPreviousNode(current); //connects the current Node to the better neighbor Node
neighbor.setDistanceFromStart(neighborDistanceFromStart);
neighbor.setHeuristic(getManhattanDistance(neighbor.getCol(), neighbor.getRow(), goalX, goalY));
}
I belive this may be caused because, since each enemy will only find the path when the player's coordinates have changed since the previous pathfinding, once the player moves, each enemy pathfinds at the exact same time, calling findPath(), and does calculations on the same Node's, mixing up the previous Nodes.
How can I prevent this from happening? I've thought of, instead of setting a previous node in findPath(), just adding it to the path to return.
Tested above out and didn't work, as I believe there were multiple neighbor Node's that were "better" than the current Node being calculated, resulting in the same Node being in the path multiple times.