Search code examples
path-findinga-star

Strange behaviour in A* pathfinding


Please watch this GIF for better understanding
.

I am encountering this strange behaviour in A* pathfinding. One thing I've got to say is that my G-cost formula is just

distance(this, startNode)

I have a problem in understanding proper G-cost formula. Please correct me, because im probably wrong. So the G-cost of the current node should be

this.gCost = parent.gCost + distance(this, parent);

Where distance(this, parent) returns either 10 or 14. In this way gCost will be calculated by following the path made by parents and not the shortest path? Am I right?

Also - once parent is set, I do not update it - I think this is the main problem. Could you explain me in pseudo-code when to change node's parent?


Solution

  • Yes, that's the correct way to calculate g-cost. As for updating the parent, you do it when the g-cost you've calculated is lower than the previous g-cost for that node.

    If it helps, think of nodes as starting out with a g-cost of infinity, and you set the parent of a node whenever you can lower the node's g-cost.