Ejemplo n.º 1
0
    static public List <Vector2> FindPath(
        Vector2 start,
        Vector2 end,
        bool flying = false)
    {
        Vector2 startTile = map.getTileFromPosition(start.x, start.y);
        Vector2 endTile   = map.getTileFromPosition(end.x, end.y);

        if ((map.getTileTypeFromPosition(end.x, end.y) != MapGeneration.TileType.Ground ||
             map.getTileTypeFromPosition(start.x, start.y) != MapGeneration.TileType.Ground) &&
            !flying)
        {
            return(null);
        }
        openList.Clear();
        nodeCosts.Clear();
        nodeStatus.Clear();
        PathNode startNode;
        PathNode endNode;

        endNode   = new PathNode(null, null, endTile, 0);
        startNode = new PathNode(null, endNode, startTile, 0);
        addNodeToOpenList(startNode);
        while (openList.Count > 0)
        {
            PathNode currentNode = openList[openList.Count - 1];
            if (currentNode.IsEqualToNode(endNode))
            {
                List <Vector2> bestPath = new List <Vector2>();
                while (currentNode != null)
                {
                    bestPath.Insert(0, currentNode.GridLocation);
                    currentNode = currentNode.ParentNode;
                }
                return(bestPath);
            }
            openList.Remove(currentNode);
            nodeCosts.Remove(currentNode.GridLocation);
            foreach (PathNode possibleNode in findAdjacentNodes(currentNode, endNode, flying))
            {
                if (nodeStatus.ContainsKey(possibleNode.GridLocation))
                {
                    if (nodeStatus[possibleNode.GridLocation] ==
                        NodeStatus.Closed)
                    {
                        continue;
                    }
                    if (
                        nodeStatus[possibleNode.GridLocation] ==
                        NodeStatus.Open)
                    {
                        if (possibleNode.TotalCost >=
                            nodeCosts[possibleNode.GridLocation])
                        {
                            continue;
                        }
                    }
                }
                addNodeToOpenList(possibleNode);
            }
            nodeStatus[currentNode.GridLocation] = NodeStatus.Closed;
        }
        return(null);
    }