gpt4 book ai didi

c# - 使用 TreeInstance 将树添加到 Terrain C#

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:03 27 4
gpt4 key购买 nike

我尝试使用以下代码将树木添加到我的地形中:

// Create Trees
for (int x = 0; x < terrainData.heightmapWidth; x++)
{
for (int z = 0; z < terrainData.heightmapWidth; z++)
{
if (GetBiome(x, z) == "Grasland")
{
int r = UnityEngine.Random.Range(0, 500);
if (r == 0)
{
Terrain terrain = GetComponent<Terrain>();
TreeInstance treeTemp = new TreeInstance();
treeTemp.position = new Vector3(x, 0, z);
treeTemp.prototypeIndex = 0;
treeTemp.widthScale = 1f;
treeTemp.heightScale = 1f;
treeTemp.color = Color.white;
treeTemp.lightmapColor = Color.white;
terrain.AddTreeInstance(treeTemp);
terrain.Flush();
}
}
}
}

函数 GetBiome() 工作正常,我通过将树作为游戏对象来检查它工作正常。

是否缺少我没有想到的东西?

因为没有生成一棵树。

我要生成的树是在 PaintTrees 下设置的:

enter image description here

最佳答案

请阅读我的注释作为下面的评论,我希望这能解释并解决问题。我已经统一测试了这一点以确认。

// Create Trees

//make these float otherwise your position math below is truncated
for (float x = 0; x < terrainData.heightmapWidth; x++)
{
//heightmapHeight not heightmapWidth
for (float z = 0; z < terrainData.heightmapHeight; z++)
{
Terrain terrain = GetComponent<Terrain>();
int r = UnityEngine.Random.Range(0, 500);
if (r == 0)
{
TreeInstance treeTemp = new TreeInstance

//position is local and expects value between 0 and 1
treeTemp.position = new Vector3(x / terrainData.heightmapWidth, 0, z / terrainData.heightmapHeight),

treeTemp.prototypeIndex = 0;
treeTemp.widthScale = 1f;
treeTemp.heightScale = 1f;
treeTemp.color = Color.white;
treeTemp.lightmapColor = Color.white;
terrain.AddTreeInstance(treeTemp);
terrain.Flush();
}
}
}

关于c# - 使用 TreeInstance 将树添加到 Terrain C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53880451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com