Пример #1
0
    IEnumerator CheckIfPathExists(Vector2 startPos, Vector2 targetPos)
    {
        bool pathSuccess = false;

        //Get the nodes for respective world space positions.
        Node startNode  = Grid.NodeFromWorldPoint(startPos);
        Node targetNode = Grid.NodeFromWorldPoint(targetPos);

        //Create open set and closed set. Open set for nodes that haven't been examined yet, closed set for nodes that have.
        Heap <Node>    openSet   = new Heap <Node>(grid.MaxSize);
        HashSet <Node> closedSet = new HashSet <Node>();

        //Add start node to openSet
        openSet.Add(startNode);

        while (openSet.Count > 0)
        {
            Node currentNode = openSet.RemoveFirst();
            closedSet.Add(currentNode);

            //We've found the target
            if (currentNode == targetNode)
            {
                pathSuccess = true;
                break;
            }

            //Find all neighbouring nodes.
            List <Node> neighbours = new List <Node>();
            neighbours = Grid.GetNeighbourNodes(currentNode);
            foreach (Node neighbour in neighbours)
            {
                //If the node is walkable or it is in the closed set, then continue to the next
                if (!neighbour.walkable || closedSet.Contains(neighbour))
                {
                    continue;
                }

                int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour);
                if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
                {
                    neighbour.gCost  = newMovementCostToNeighbour;
                    neighbour.hCost  = GetDistance(neighbour, targetNode);
                    neighbour.parent = currentNode;
                    if (!openSet.Contains(neighbour))
                    {
                        openSet.Add(neighbour);
                    }
                }
            }
        }
        yield return(null);

        requestManager.FinishedCheckingPath(null, pathSuccess);
    }