Difficulty with Pathfinding - Please Help!

So I’m working on implementing pathfinding from this excellent tutorial. The problem is that I feel I’ve implemented the algorithm perfectly, yet I get different results in the pathfinding than what is advertised. Specifically, rather than taking what appears to be the shortest path, the pathfinding will take the widest possible path. For example:

Here, the purple is the more logical path that it SHOULD take from start (red) to goal (blue), but instead it takes the RED path, which may take an equal number of steps, but it looks ridiculous for a character to walk in at right angles like that.

I’m pulling my hair out trying to determine what’s wrong, and I just can’t see the problem. Like I said, I implemented the algorithms for the Breadth-First Search exactly (so far as I can tell), and as I step through the code, it seems to do the right thing (each iteration, the current block’s neighbors are added to a queue and to a dictionary that shows where the neighbors were discovered from), yet I get different results than the examples on the tutorial page.

Please see the link above (around the area that has an image similar to the one I inserted) and my code below. I’m using a custom struct called IntVector2 that works like a Vector2, but with integers. The user passes a starting position into GetRoute along with the target position and a graph size. The GetRoute method splits the work of a long path across multiple checks along grids of graphSize x graphSize tiles, to reduce the size of the pathfinding over large distances. GetRoute() returns a list of IntVector2s (x/y coordinates) that the character follows one after the other.

PLEASE let me know if you have ANY idea what may be wrong! I’m at wits end!

using UnityEngine;
using System.Collections.Generic;

static class Pathfinding
{
    public static List<IntVector2> GetRoute(IntVector2 startNode, IntVector2 targetNode, int graphSize) {
        List<IntVector2> route = new List<IntVector2>(); // route to return
        List<IntVector2> subroute = new List<IntVector2>();

        subroute.Add(startNode); // initialize with starting node
        while (subroute[subroute.Count - 1] != targetNode) { // continue finding subroutes until a subroute ends at the target node
            subroute = GetSubroute(subroute[subroute.Count - 1], targetNode, graphSize); // find next subroute
            route.AddRange(subroute); // add subroute to route
        }

        return route;
    }

    private static List<IntVector2> GetSubroute(IntVector2 startNode, IntVector2 targetNode, int graphSize) {
        IntVector2 corner = new IntVector2(startNode.x - Mathf.Max(graphSize / 2), startNode.y - Mathf.Max(graphSize / 2));

        if (!LocationInRange(targetNode, corner, graphSize))
            targetNode = GetClosestTarget(targetNode, corner, graphSize);

        Queue<IntVector2> frontier = new Queue<IntVector2>();
        frontier.Enqueue(startNode); // add current position
        Dictionary<IntVector2, IntVector2> cameFrom = new Dictionary<IntVector2, IntVector2>(); // create dictionary of previous locations

        IntVector2 current;
        while (frontier.Count > 0) { // until all locations are accounted for...
            current = frontier.Dequeue(); // get next location

            if (current == targetNode) // if location is the goal, break early
                break;

            foreach (IntVector2 next in GetNeighbors(current, corner, graphSize)) { // for each neighbor location

                if (!cameFrom.ContainsKey(next) && next != startNode) { // if location hasn't been used and isn't the starting point...
                    frontier.Enqueue(next); // check location's neighbors later
                    cameFrom.Add(next, current); // add location's direction
                }
            }
        }

        List<IntVector2> route = new List<IntVector2>();
        current = targetNode; // start at the end goal

        while (current != startNode) { // while current node isn't the starting node
            route.Add(current); // add current node to route
            current = cameFrom[current]; // current node is the previous node
        }
        route.Reverse(); // reverse route to get steps from start to goal

        return route;
    }

    private static List<IntVector2> GetNeighbors(IntVector2 current, IntVector2 corner, int graphSize) {
        List<IntVector2> returnList = new List<IntVector2>();

        if (current.x < corner.x + graphSize) // if not already at edge of graph, get right neighbor
            returnList.Add(current + IntVector2.right);

        if (current.y < corner.y + graphSize) // if not already at edge of graph, get upper neighbor
            returnList.Add(current + IntVector2.up);

        if (current.x > corner.x) // if not already at edge of graph, get left neighbor
            returnList.Add(current + IntVector2.left);

        if (current.y > corner.y) // if not already at edge of graph, get lower neighbor
            returnList.Add(current + IntVector2.down);

        return returnList;
    }

    private static bool LocationInRange(IntVector2 location, IntVector2 corner, int graphSize) {
        return (location.x >= corner.x // is the location within the bounds of the graph?
            && location.y >= corner.y
            && location.x <= corner.x + graphSize
            && location.y <= corner.y + graphSize);
    }

    private static IntVector2 GetClosestTarget(IntVector2 goal, IntVector2 corner, int graphSize) {
        return new IntVector2(Mathf.Clamp(goal.x, corner.x, corner.x + graphSize),
            Mathf.Clamp(goal.y, corner.y, corner.y + graphSize)); // find point nearest the goal within the graph
    }
}

P.S. If you’re thinking that the problem is that the work is divided into sub-routes, I don’t think that’s the problem, because the awkward pathing issue occurs even if the goal is within a single graphSize x graphSize grid.

Problem is that the distance on both paths is the same. Both paths are legitimate shortest paths. And the algorithm simply returns the first one it finds.

If you were to allow diagonal movement then the diagonal path would be shorter. But with only 90 degree movement the paths are the same length.

Is there some way to weigh the algorithm to prefer the zig-zag paths rather than direct right-angle paths? In the linked tutorial article, his pathfinding always seems to prefer the zig-zag path, yet when I implement the algorithm, it never zig-zags.

Are you using A*? I haven’t read through your code to check.

With A* you can modify your heuristic function to use the actual straight line distance rather then the Manhattan distance. That way the diagonal path will be checked first.

At the moment, I’m using a simple Breadth-first search. If A* is able to better create paths, then it comes down to the algorithm and not implementation of the above Breadth-first search, so that will be good to know.

This post is mostly to ask if there’s something wrong with my implementation, but if breadth-first search just gives messy results, then that’s another matter.

It is an artefact of the search algorithm. You could mix it up a little by randomising the order of the neighbours before adding them to the frontier list. But the results will still be messy.

A guided search algorithm like A* is going to preform better in almost all realistic game situations. And you can mess with path weights to get the desired behaviour.

1 Like

Thank you for the information!