Пример #1
0
    public List <Tile> FindPath(Vector3 startPos, Vector3 endPos)
    {
        Tile startTile = generator.TileFromWorldPoint(startPos);
        Tile endTile   = generator.TileFromWorldPoint(endPos);

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

        openSet.Add(startTile);

        while (openSet.Count > 0)
        {
            Tile currentTile = openSet[0];
            foreach (Tile t in openSet)
            {
                if (t.fScore < currentTile.fScore || t.fScore == currentTile.fScore && t.hScore < currentTile.hScore)
                {
                    currentTile = t;
                }
            }

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

            if (currentTile == endTile)
            {
                ReconstructPath(startTile, endTile);
                return(path);
            }

            List <Tile> neighbours = generator.GetNeighbours(currentTile);
            foreach (Tile neighbour in neighbours)
            {
                if (neighbour.tileType == TileType.Type.ROCK || closedSet.Contains(neighbour))
                {
                    continue;
                }

                int newGScore = currentTile.gScore + GetDistance(currentTile, neighbour);
                if (newGScore < currentTile.gScore || !openSet.Contains(neighbour))
                {
                    neighbour.gScore = newGScore;
                    neighbour.hScore = GetDistance(neighbour, endTile);
                    neighbour.parent = currentTile;

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

        return(null);
    }