提问人:kayardurdass 提问时间:8/31/2023 最后编辑:kayardurdass 更新时间:9/1/2023 访问量:31
尝试在地形上统一实例化成批的花朵
Trying to instantiate batches of flower on a terrain in unity
问:
所以,我有一个地形,我正在尝试在我的地形上添加小批量的花朵,我写了这段代码,但是当我启动我的游戏时,它会加载到无穷大,你能帮我吗? 这是我的代码的一部分,当我在游戏启动时将其删除时,它会实例化花朵。
Vector2[] FlowerPatch = { };
bool done = false;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
animator = GetComponent<Animator>();
TerrainData terrainData = Terrain.activeTerrain.terrainData;
for (int i = 0; i < 1; i++)
{
int nFlowers = Random.Range(1, 5);
Vector2 patchPos = new Vector2(0, 0);
Debug.Log("Not Done");
while (!done)
{
int x = Random.Range(0, 1000);
int y = Random.Range(0, 1000);
Vector2 pos = new Vector2(x, y);
Debug.Log("Searching Position");
for (int i1 = 0; i1 < FlowerPatch.Length; i1++)
{
if (Mathf.Sqrt(Mathf.Pow(pos.x - FlowerPatch[i1].x, 2) + Mathf.Pow(pos.y - FlowerPatch[i1].y, 2)) > 2)
{
done = true;
patchPos = pos;
FlowerPatch.Append(pos);
}
else done = false;
}
}
for (int j = 0; j < nFlowers; j++)
{
Vector3 FlowerPos = new Vector3(patchPos.x + Random.Range(-1.0f, 1.0f), 0, patchPos.y + Random.Range(-1.0f, 1.0f));
FlowerPos.y = terrainData.GetHeight((int)FlowerPos.x, (int)FlowerPos.z);
Instantiate(flower, FlowerPos, Quaternion.identity);
Debug.Log("Instantiated Flower");
}
}
}
我将不胜感激任何关于如何解决我的问题的建议:)
我尝试将我的代码移动到更新函数以降低我想要的批次数,但没有任何效果
编辑: 按照您的建议尝试了一些方法,但仍然不起作用
for (int i = 0; i < 2500; i++)
{
int nFlowers = Random.Range(1, 5);
Vector2 patchPos = new Vector2(0, 0);
Debug.Log("Not Done");
while (!done)
{
int x = Random.Range(0, 1000);
int y = Random.Range(0, 1000);
Vector2 pos = new Vector2(x, y);
Debug.Log("Searching Position");
for (int i1 = 0; i1 < FlowerPatch.Length; i1++)
{
if (Mathf.Sqrt(Mathf.Pow(pos.x - FlowerPatch[i1].x, 2) + Mathf.Pow(pos.y - FlowerPatch[i1].y, 2)) > 2)
{
done = true;
patchPos = pos;
break;
}
else done = false;
}
}
for (int j = 0; j < nFlowers; j++)
{
Vector3 FlowerPos = new Vector3(patchPos.x + Random.Range(-1.0f, 1.0f), 0, patchPos.y + Random.Range(-1.0f, 1.0f));
FlowerPatch.Append(patchPos);
FlowerPos.y = terrainData.GetHeight((int)FlowerPos.x, (int)FlowerPos.z);
Instantiate(flower, FlowerPos, Quaternion.identity);
Debug.Log("Instantiated Flower");
}
}
答: 暂无答案
评论
Append