Exemplo n.º 1
0
    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);

        if (startNode == null || targetNode == null)
        {
            return(null);
        }

        // First step
        // Update H value of all the nodes in the grid
        grid.ResetNodesParent();
        grid.ScanObstacles();
        if (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);

            // Ajout des noeuds voisins dans l'open list s'ils n'existent pas
            List <Node> neighbours = grid.GetNeighbours(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);
                }
            }
            // Choose the node with the lower F cost
            currentNode = GetBestCandidate(openList, targetNode);
            cpt++;
            if (cpt > limitStepAlgo)
            {
                Debug.Log("Reached iteration limit during pathFinding algorithm");
                return(null);
            }
        }
        Debug.Log("number of iterations: " + cpt);
        Queue <Node> path = GetPathFromNode(currentNode);

        currentPath = path;
        return(path);
    }