简体   繁体   English

如何在给定的体积/区域 3d 中生成对象

[英]How can I spawn objects in a given volume/area 3d

I was given a task by my teacher to make a script to spawn object RANDOMLY in a given AREA 3D either in a rectangle or in a sphere, I know how to do that but have no idea how to make it choose random place in the area.我的老师给了我一个任务,让我编写一个脚本,以在矩形或球体中的给定 AREA 3D 中随机生成对象,我知道如何做到这一点,但不知道如何让它选择该区域中的随机位置.

Thanks.谢谢。

Measure the range (x-axis, y-axis, z-axis) in Unity, and then use time to control how often it is generated.在 Unity 中测量范围(x 轴、y 轴、z 轴),然后使用时间来控制生成的频率。 These are randomly generated codes, don't forget to drag the prefab to the cube这些是随机生成的代码,不要忘记将预制件拖到立方体上

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

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM