我的老師給了我一個任務,讓我撰寫一個腳本以在給定的 3D 區域中隨機生成物件,我知道如何做到這一點,但不知道是否在給定的半徑內隨機生成,請幫助 :(。
謝謝。
uj5u.com熱心網友回復:
在 Unity 中測量范圍(x 軸、y 軸、z 軸),然后使用時間來控制生成的頻率。這些是隨機生成的代碼,不要忘記將預制件拖到立方體上
public GameObject cube;//Define a cube to store the prefab to be randomly generated
private float t1, t2;// Control how often to generate by time
void Start()
{
t1 = 0;//time when the game starts
}
void Update()
{
t2 = Time.fixedTime;//The time when the game progresses to a certain position
if (t2 - t1 >= 2)
{
x = Random.Range(-50,50);//Specify the range in the x-axis direction
z = Random.Range(-50,50);//Specify the range in the z-axis direction
//Specify the scope according to the actual situation of your own scene
Instantiate(cube, new Vector3(x, 0.5f, z), Quaternion.identity);// Randomly generate objects (prefab, generated position, orientation).
t1 = t2;//Every time it is generated, let t1=t2
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439969.html
