如何return 高效地基于高度图进行平铺?

How to return tile based on heightmap efficiently?

我正在程序化地生成一个世界,对于 Tilemap 中的每个位置,我调用此函数以获得与高度匹配的图块类型:

public static NaturalTile GetNaturalTileByHeight(float height)
{
    SortedDictionary<float, NaturalTile> tilesByHeight = new SortedDictionary<float, NaturalTile>();

    foreach (var tile in NaturalTileTypes)
    {
        if (tile.MaxGenHeight > 0) tilesByHeight.Add(tile.MaxGenHeight, tile);
    }

    foreach (var tile in tilesByHeight)
    {
        if (height <= tile.Key) return tile.Value;
    }

    return null;
}

对于每个图块,我必须先创建一个排序字典,以便按高度排序。然后,我必须用基于高度的图块填充已排序的字典。最后,我将高度与已排序字典中的每个图块进行比较,由于它是按高度排序的,因此它总是 return 较低值的图块排在第一位,这使其正常工作。

我觉得这太复杂了,即使它只在世界生成时发生一次。

非常感谢任何改进建议。

您不需要单独对它们进行排序。只需在一个循环中找到最好的图块(MaxGenHeight 在参数 height 之上,但最接近它)。

public static NaturalTile GetNaturalTileByHeight(float height)
{
    NaturalTile bestTile = null;
    foreach (var tile in NaturalTileTypes)
    {
        // Is this tile type valid for the given height?
        if (tile.MaxGenHeight > 0 && tile.MaxGenHeight >= height)
        {
            // Is it better than the current best tile?
            if (bestTile == null || tile.MaxGenHeight < bestTile.MaxGenHeight)
            {
                bestTile = tile;
            }
        }
    }

    return bestTile;
}