Beispiel #1
0
    // finds a path between two positions in the graph
    public List <PathNode> FindPath(Vector2Int startPos, Vector2Int endPos)
    {
        // get the first Node (startPos) and add it to open list
        PathNode startNode = GetNode(startPos.x, startPos.y);
        PathNode endNode   = GetNode(endPos.x, endPos.y);

        openList = new List <PathNode> {
            startNode
        };
        closedList = new List <PathNode>();

        for (int x = 0; x < grid.GetWidth(); x++)
        {
            for (int y = 0; y < grid.GetHeight(); y++)
            {
                PathNode pathNode = GetNode(x, y);
                pathNode.gCost = int.MaxValue;
                pathNode.CalculateFCost();
                pathNode.cameFromNode = null;
            }
        }

        startNode.gCost = 0;
        startNode.hCost = CalculateDistanceCost(startNode, endNode);
        startNode.CalculateFCost();


        // CYCLE:
        while (openList.Count > 0)
        {
            PathNode currNode = GetLowestFCostNode(openList);
            if (currNode == endNode)
            {
                // reached final node
                return(CalculatePath(endNode));
            }

            openList.Remove(currNode);
            closedList.Add(currNode);

            foreach (PathNode neighborNode in GetNeighbors(currNode))
            {
                if (closedList.Contains(neighborNode))
                {
                    continue;
                }
                // ignores nodes that are not walkable
                if (!neighborNode.isWalkable)
                {
                    closedList.Add(neighborNode);
                    continue;
                }

                int tentCost = currNode.gCost + CalculateDistanceCost(currNode, neighborNode);
                if (tentCost < neighborNode.gCost)
                {
                    neighborNode.cameFromNode = currNode;
                    neighborNode.gCost        = tentCost;
                    neighborNode.hCost        = CalculateDistanceCost(neighborNode, endNode);
                    neighborNode.CalculateFCost();

                    if (!openList.Contains(neighborNode))
                    {
                        openList.Add(neighborNode);
                    }
                }
            }
        }

        // Out of nodes in open list!
        return(null);
    }
Beispiel #2
0
    private void UpdateVisual()
    {
        int quadCount = grid.GetWidth() * grid.GetHeight();

        MeshUtils.CreateEmptyMeshArrays(quadCount, out Vector3[] vertices, out Vector2[] uv, out int[] triangles);