问题描述
我正在按程序生成一个世界,对于 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;
}
对于每个磁贴,我必须首先创建一个排序字典,以便按高度排序。然后,我必须用基于高度的瓷砖填充排序的字典。最后,我将高度与排序字典中的每个 tile 进行比较,因为它是按高度排序的,所以它总是首先返回值较低的 tile,这使它正常工作。
我觉得这太复杂了,即使它只在世界生成中发生一次。
非常感谢任何改进建议。
解决方法
您不需要分别对它们进行排序。只需在一个循环中找到最好的图块(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;
}