Пример #1
0
        private IEnumerator FindPath(Vector3 startPosition, Vector3 targetPosition)
        {
            Vector2[] waypoints   = new Vector2[0];
            bool      pathSuccess = false;

            Node startNode  = grid.NodeFromWorldPoint(startPosition);
            Node targetNode = grid.GetNearestWalkableNode(grid.NodeFromWorldPoint(targetPosition), 5);

            Heap <Node>    openSet   = new Heap <Node>(grid.MaxSize);
            HashSet <Node> closedSet = new HashSet <Node>();

            openSet.Add(startNode);

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

                if (currentNode == targetNode)
                {
                    pathSuccess = true;
                    break;
                }

                foreach (Node neighbour in grid.GetNeighours(currentNode))
                {
                    if (!neighbour.walkable || closedSet.Contains(neighbour))
                    {
                        continue;
                    }

                    int  newMovementCost        = GetDistance(currentNode, neighbour) + currentNode.gCost;
                    bool neighbourWithinOpenSet = openSet.Contains(neighbour);
                    if (newMovementCost < neighbour.gCost || !neighbourWithinOpenSet)
                    {
                        neighbour.gCost  = newMovementCost;
                        neighbour.hCost  = GetDistance(neighbour, targetNode);
                        neighbour.parent = currentNode;

                        if (!neighbourWithinOpenSet)
                        {
                            openSet.Add(neighbour);
                            openSet.UpdateItem(neighbour);
                        }
                    }
                }
            }

            yield return(null);

            if (pathSuccess)
            {
                waypoints = RetracePath(startNode, targetNode);
            }

            pathRequestManager.FinishedProcessingPath(waypoints, pathSuccess);
        }