public static Vector3[] Rotation = new Vector3[5] { Vector3.one, new Vector3(0, 90, 0), new Vector3(0, -90, 0), Vector3.zero, new Vector3(0, 180, 0) };    //这里用来表示汽车的朝向 E W N S
public static Vector3[] Dir = new Vector3[5] { Vector3.one, new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1) };
public GameObject CarPfab;
public GameObject CarGongju;
public Transform CarParent;

void SpawnCars()
{
    //在场景中随机生成汽车,数量为10
    for (int i = 0; i < 10; i++)
    {
        //随机生成位置和朝向
        Vector3 pos = new Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
        int rotIndex = Random.Range(0, 5);
        Quaternion rot = Quaternion.Euler(Rotation[rotIndex]);

        //创建汽车
        GameObject carObj = Instantiate(CarPfab, pos, rot, CarParent);

        //设置汽车的朝向和速度
        CarController car = carObj.GetComponent<CarController>();
        car.direction = Dir[rotIndex];
        car.speed = Random.Range(5, 10);

        //将汽车添加到工具类中
        CarGongju.Instance.AddCar(car);
    }
}
Unity3D 随机生成汽车并控制方向和速度

原文地址: https://www.cveoy.top/t/topic/nvez 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录