Beispiel #1
0
    public List <Tile> FindPath(Tile startTile, Tile targetTile, int maxDistance, HashSet <Tile.TileState> nonWalkableTiles)
    {
        // Create the two containers necessary for the pathing algorithm
        Heap <PathingTile>    openSet   = new Heap <PathingTile> (xSize * ySize);
        HashSet <PathingTile> closedSet = new HashSet <PathingTile> ();

        // Create PathingTile equivalent of the startTile
        PathingTile startPath = new PathingTile(startTile);

        // Start off by adding the starting location to the openSet
        openSet.Add(startPath);

        // Loop until the openSet is empty or a path has been found
        while (openSet.Count > 0)
        {
            // Due to our beautiful heap, currentTile is the tile with the current shortest path
            PathingTile currentTile = openSet.RemoveFirst();
            closedSet.Add(currentTile);

            // Wow we found the path!  killer.
            if (currentTile.location == targetTile.location)
            {
                return(RetracePath(startPath, currentTile));
            }

            foreach (Tile neighbor in GetNeighbors(tileMap [currentTile.location.x, currentTile.location.y]))
            {
                PathingTile neighborTile = new PathingTile(neighbor);

                // If we cant walk on it or if we have already checked it, dont add it again to the openSet
                if (nonWalkableTiles.Contains(neighbor.curTileState) || closedSet.Contains(neighborTile))
                {
                    continue;
                }

                int newCostToNeighbor = currentTile.pathWeight + GetTravelCost(tileMap [currentTile.location.x, currentTile.location.y], neighbor);
                if (newCostToNeighbor <= maxDistance && (newCostToNeighbor < neighborTile.pathWeight || !openSet.Contains(neighborTile)))
                {
                    neighborTile.pathWeight = newCostToNeighbor;
                    neighborTile.parent     = currentTile;
                    openSet.Add(neighborTile);
                }
            }
        }
        // If we hit this point in the code, no path was found to the target tile
        if (debugLogs)
        {
            Debug.Log("No path found");
        }
        return(null);
    }
Beispiel #2
0
    List <Tile> RetracePath(PathingTile start, PathingTile end)
    {
        List <Tile> path        = new List <Tile> ();
        PathingTile currentTile = end;

        // Trace backwards and add all the tiles to path
        while (currentTile != start)
        {
            path.Add(tileMap[currentTile.location.x, currentTile.location.y]);
            currentTile = currentTile.parent;
        }

        // Now path is actually the reversed version of how we want to move, so fix that
        path.Reverse();
        return(path);
    }