예제 #1
0
    // Get the path to follow using a A* start algorithm
    public Queue <Node> GetPathWithAStarAlgo(Vector2 startPos, Vector2 targetPos)
    {
        List <Node> openList  = new List <Node>();
        List <Node> closeList = new List <Node>();

        Node startNode  = grid.GetNodeFromWorldPosition(startPos);
        Node targetNode = grid.GetNodeFromWorldPosition(targetPos);

        // First step
        // Update H value of all the nodes in the grid
        grid.ResetNodesParent();
        grid.ScanObstacles();
        if (targetNode == null || startNode == null || targetNode.isWall)
        {
            return(null);
        }

        foreach (Node node in grid.GetNodes())
        {
            if (node != null)
            {
                node.UpdateHCost(targetNode);
            }
        }
        Node currentNode = startNode;
        int  cpt         = 0;

        while (currentNode != targetNode)
        {
            openList.Remove(currentNode);
            closeList.AddUnique(currentNode);

            // Add neighbour nodes to the open list if they are not in the closeList
            List <Node> neighbours = grid.GetFreeNeighbours(currentNode);
            foreach (Node node in neighbours)
            {
                if (!closeList.Contains(node))
                {
                    // We change the parent node if it is a shorter way to access
                    if (node.parent == null || node.GCost > node.ComputeGCostFrom(currentNode))
                    {
                        node.parent = currentNode;
                    }
                    openList.AddUnique(node);
                }
            }
            currentNode = GetBestCandidate(openList, targetNode);
            cpt++;
            if (cpt > limitStepAlgo)
            {
                Debug.Log("Reached iteration limit during pathFinding algorithm");
                return(null);
            }
        }
        //Debug.Log("number of iterations: " + cpt);
        currentPath = GetPathFromNode(currentNode);
        return(currentPath);
    }