예제 #1
0
    public List <ClickableTile> CalculateShortestPath(ClickableTile origin, ClickableTile destination)
    {
        List <ClickableTile> pendingTiles          = new List <ClickableTile> ();
        List <ClickableTile> alreadyInspectedTiles = new List <ClickableTile> ();

        pendingTiles.Add(origin);

        while (pendingTiles.Count > 0)
        {
            ClickableTile currentTile = pendingTiles [0];
            for (int i = 0; i < pendingTiles.Count; i++)
            {
                if (pendingTiles[i].GetFCost() < currentTile.GetFCost() ||
                    pendingTiles [i].GetFCost() == currentTile.GetFCost() && pendingTiles[i].hCost < currentTile.hCost)
                {
                    currentTile = pendingTiles [i];
                }
            }
            pendingTiles.Remove(currentTile);
            alreadyInspectedTiles.Add(currentTile);

            if (currentTile == destination)
            {
                return(RetracePath(origin, destination));
            }

            foreach (ClickableTile neighbor in currentTile.neighbors)
            {
                if (alreadyInspectedTiles.Contains(neighbor) ||
                    neighbor.GetUnitAssigned() != null && neighbor.GetUnitAssigned().propietary != GameManager.instance.unitSelected.propietary)
                {
                    continue;
                }

                int newMovementCostToNeighbor = currentTile.gCost + GetCostForMovementType((int)GameManager.instance.unitSelected.movementType, (int)neighbor.typeOfTerrain.terrainName);
                if (newMovementCostToNeighbor < neighbor.gCost ||
                    pendingTiles.Contains(neighbor) == false)
                {
                    neighbor.gCost  = newMovementCostToNeighbor;
                    neighbor.hCost  = GetHCost(neighbor, destination);
                    neighbor.parent = currentTile;
                    if (pendingTiles.Contains(neighbor) == false)
                    {
                        pendingTiles.Add(neighbor);
                    }
                }
            }
        }

        //It should never get here
        Debug.LogError("Something went wrong with the A* algorithm");
        return(null);
    }