Exemple #1
0
    void FindPath(Vector2 startPosition, Vector2 targetPosition)
    {
        PathfindingNode startNode  = grid.GetNodeFromWorldPoint(startPosition);
        PathfindingNode targetNode = grid.GetNodeFromWorldPoint(targetPosition);

        List <PathfindingNode>    openSet   = new List <PathfindingNode>();
        HashSet <PathfindingNode> closedSet = new HashSet <PathfindingNode>();

        openSet.Add(startNode);

        while (openSet.Count > 0)
        {
            PathfindingNode currentNode = openSet[0];
            for (int i = 0; i < openSet.Count; i++)
            {
                if (openSet[i].fCost < currentNode.fCost ||
                    openSet[i].fCost == currentNode.fCost)
                {
                    if (openSet[i].hCost < currentNode.hCost)
                    {
                        currentNode = openSet[i];
                    }
                }

                openSet.Remove(currentNode);
                closedSet.Add(currentNode);

                if (currentNode == targetNode)
                {
                    RetracePath(startNode, targetNode);
                    return;
                }

                foreach (PathfindingNode neighbor in grid.GetNeighbors(currentNode))
                {
                    if (!neighbor.isWalkable || closedSet.Contains(neighbor))
                    {
                        continue;
                    }

                    int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor);

                    if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor))
                    {
                        neighbor.gCost  = newMovementCostToNeighbor;
                        neighbor.hCost  = GetDistance(neighbor, targetNode);
                        neighbor.parent = currentNode;

                        if (!openSet.Contains(neighbor))
                        {
                            openSet.Add(neighbor);
                        }
                    }
                }
            }
        }
    }