示例#1
0
    public static ArrayList FindPath(Node startNode, Node endNode)
    {
        NodeList openList  = new NodeList();            // New neighbour node
        NodeList closeList = new NodeList();            // Node alreadly processed

        // GridManager gridManager = GameObject.FindGameObjectWithTag ("GridManager").GetComponent <GridManager> ();
        GridManager gridManager = GameObject.FindObjectOfType(typeof(GridManager)) as GridManager;

        gridManager.ClearNodeHistory();

        // Add the start node
        startNode.gCost = 0;
        startNode.fCost = startNode.gCost + HeuristicCost(startNode, endNode);
        openList.Push(startNode);

        while (openList.GetFirstNode() != null)
        {
            Node currentNode = openList.GetFirstNode();

            if (currentNode == endNode)
            {
                return(GetPathList(endNode));
            }

            ArrayList neighbourNodes = gridManager.GetNeighbourNodes(currentNode);

            foreach (Node neighbourNode in neighbourNodes)
            {
                if (!closeList.Contain(neighbourNode))                  // Skip if processed before
                {
                    float gCost = currentNode.gCost + OneStepCost(currentNode, neighbourNode);
                    float fCost = gCost + HeuristicCost(neighbourNode, endNode);

                    // Update if neighbour node is not contained in openlist
                    // or new fCost is lower than the before
                    if (!openList.Contain(neighbourNode) || fCost < neighbourNode.fCost)
                    {
                        neighbourNode.parentNode = currentNode;
                        neighbourNode.gCost      = gCost;
                        neighbourNode.fCost      = fCost;

                        // Add if neighbour node is not contained in openlist
                        if (!openList.Contain(neighbourNode))
                        {
                            openList.Push(neighbourNode);
                        }
                    }
                }
            }

            // Manipulate list
            openList.Pop(currentNode);
            closeList.Push(currentNode);
        }

        return(GetPathList(endNode));
    }