I'm trying to implement the a* pathfinding algorithm in my game. I've looked at dozens of tutorials but I can't seem to get it right. My code is below, and It's not working... does anybody see something I'm doing wrong? Mainly, I followed these tutorials: Tutorial 1 Tutorial 2
I'm sure you will be able to understand all of the classes/methods I've created. If you can look over this code and just tell me if it looks remotely correct that would be great.
public void highlightPath(Tile start, Tile end)
{
AStar astar = new AStar();
Tile currentTile = start;
Tile endTile = end;
start.node.g = 0;
start.node.h = astar.getHeuristic(start.getCoordinates(), endTile.getCoordinates());
start.node.parent = null;//for the loop
astar.openList.add(start);
while(!astar.openList.isEmpty())
{
currentTile = astar.getTileWithLowestF();
if(currentTile==endTile)
break;
astar.openList.remove(currentTile);
astar.closedList.add(currentTile);
AdjacentTiles adjacentTiles = getAdjacentTiles2(currentTile);
//Assign G and H costs:
adjacentTiles.aboveRight.node.g = 10 + currentTile.node.g;
adjacentTiles.right.node.g = 14 + currentTile.node.g;
adjacentTiles.belowRight.node.g = 10 + currentTile.node.g;
adjacentTiles.below.node.g = 14 + currentTile.node.g;
adjacentTiles.belowLeft.node.g = 10 + currentTile.node.g;
adjacentTiles.left.node.g = 14 + currentTile.node.g;
adjacentTiles.aboveLeft.node.g = 10 + currentTile.node.g;
ArrayList<Tile> adjacentTilesList = new ArrayList<>();
adjacentTilesList.add(adjacentTiles.aboveRight);
adjacentTilesList.add(adjacentTiles.right);
adjacentTilesList.add(adjacentTiles.aboveRight);
adjacentTilesList.add(adjacentTiles.belowRight);
adjacentTilesList.add(adjacentTiles.below);
adjacentTilesList.add(adjacentTiles.belowLeft);
adjacentTilesList.add(adjacentTiles.left);
adjacentTilesList.add(adjacentTiles.aboveLeft);
for(Tile t:adjacentTilesList)
{
t.node.h = astar.getHeuristic(t.getCoordinates(), endTile.getCoordinates());
}
for(Tile t:adjacentTilesList)
{
//Check traversability:
if(t.exists == false)//Change this to test segments/elevation
continue;//skips everything below...
if(astar.closedList.contains(t) && currentTile.node.g < t.node.g)
{
t.node.g = currentTile.node.g;
t.node.parent = currentTile;
}
else if(astar.openList.contains(t) && currentTile.node.g < t.node.g)
{
t.node.g = currentTile.node.g;
t.node.parent = currentTile;
}
else
{
astar.openList.add(t);
}
}
}
Tile startingTile = start;
Tile currentTile2 = endTile;
ArrayList<Tile> path = new ArrayList<>();
path.add(currentTile2);
while(currentTile2 != start)
{
path.add(currentTile2.node.parent);
currentTile2 = currentTile2.node.parent;
}
for(Tile t:path)
{
t.highlight();
}
}