Search code examples
javaartificial-intelligencea-starpath-finding

Why does A* path finding sometimes go in straight lines and sometimes diagonals? (Java)


I'm in the process of developing a simple 2d grid based sim game, and have fully functional path finding.

I used the answer found in my previous question as my basis for implementing A* path finding. (Pathfinding 2D Java game?).

To show you really what I'm asking, I need to show you this video screen capture that I made. I was just testing to see how the person would move to a location and back again, and this was the result...

http://www.screenjelly.com/watch/Bd7d7pObyFo

Different choice of path depending on the direction, an unexpected result. Any ideas?


Solution

  • If you're looking for a simple-ish solution, may I suggest a bit of randomization?

    What I mean is this: in the cokeandcode code example, there is the nested-for-loops that generate the "successor states" (to use the AI term). I refer to the point where it loops over the 3x3 square around the "current" state, adding new locations on the pile to consider.

    A relatively simple fix would (should :)) be isolate that code a bit, and have it, say, generated a linkedlist of nodes before the rest of the processing step. Then Containers.Shuffle (or is it Generics.Shuffle?) that linked list, and continue the processing there. Basically, have a routine say, "createNaiveNeighbors(node)" that returns a LinkedList = {(node.x-1,node.y), (node.x, node.y-1)... } (please pardon the pidgin Java, I'm trying (and always failing) to be brief.

    Once you build the linked list, however, you should just be able to do a "for (Node n : myNewLinkedList)" instead of the

    for (int x=-1;x<2;x++) {
    
        for (int y=-1;y<2;y++) {
    

    And still use the exact same body code!

    What this would do, ideally, is sort of "shake up" the order of nodes considered, and create paths closer to the diagonal, but without having to change the heuristic. The paths will still be the most efficient, but usually closer to the diagonal.

    The downside is, of course, if you go from A to B multiple times, a different path may be taken. If that is unnacceptable, you may need to consider a more drastic modification.

    Hope this helps! -Agor