The A* code looked fine, but i found something you can change:
new_node.g = current_node.g + Math.floor(Math.sqrt(Math.pow(new_node.x-current_node.x, 2)+Math.pow(new_node.y-current_node.y, 2)));Because you always only take one step in any direction and the cost for each step is currently always 1 you should change it to:
new_node.g = current_node.g + 1;And when you include traffic zones you can just change it to current_node.g + new_node.traffic or whatever.
But the problem was indeed your heuristic. The function dx
2+dy
2 always overestimates the distance to the destination, which is not allowed. It even says so in the comments. So sqrt(dx
2+dy
2) should also work and give the shortest way, also it should always try to move towards the destination diagonally and make zigzag-movement, but as both diagonal and straight movement have the same cost, it doesn't matter for the overall length of the path.
The Manhattan heuristic should also NOT work, because it also overestimates the cost, because it doesn't include diagonal movement, which would be two straight moves for Manhattan.
Another heuristic you could use would be min(dx, dy): because you can move diagonally with the same cost as straight movement, only the longest distance of x and y defines the overall distance.
The code for that would be
Math.min(Math.abs(current_node.x - destination.x), Math.abs(current_node.y - destination.y))Edit:
I forgot to add this, i found a nice java applet for the comparison of different search algorithms. It is in German, but you should be able to use it without problems, i couldn't find any other with the amount of features it has.
http://www.stefan-baur.de/cs.web.mashup.pathfinding.htmlSadly you can only draw obstacles with a 3x3 brush, but it doesn't really change anything. Something nice about it is that it also shows all the nodes visited and not just the final path.