Unity脚本:多种预制体汽车从起点循环沿非闭环路径匀速行驶
```csharp using UnityEngine; using System.Collections.Generic; public class CarSpawner : MonoBehaviour { public List<GameObject> carPrefabs = new List<GameObject>(); // 汽车预制体列表 public Transform startPoint; // 起点位置 public List<Transform> pathPoints = new List<Transform>(); // 路径点列表 private List<CarMover> activeCars = new List<CarMover>(); private float spawnInterval = 2f; // 出现间隔时间 private float timeSinceLastSpawn = 0f; void Update() { timeSinceLastSpawn += Time.deltaTime; if (timeSinceLastSpawn >= spawnInterval) { SpawnCar(); timeSinceLastSpawn = 0f; } foreach (var car in activeCars) { if (!car.IsMoving) { ResetCar(car); } } } void SpawnCar() { int prefabIndex = Random.Range(0, carPrefabs.Count); GameObject carInstance = Instantiate(carPrefabs[prefabIndex], startPoint.position, Quaternion.identity); CarMover carMover = carInstance.AddComponent<CarMover>(); carMover.SetPath(pathPoints); activeCars.Add(carMover); } void ResetCar(CarMover car) { car.transform.position = startPoint.position; car.StartMovement(); } } [System.Serializable] public class CarMover : MonoBehaviour { private List<Transform> path; private int currentPointIndex = 0; public bool IsMoving { get; private set; } = true; private float speed = 5f; public void SetPath(List<Transform> newPath) { path = newPath; IsMoving = true; } void Update() { if (IsMoving && path != null && path.Count > 0) { if (currentPointIndex < path.Count) { transform.position = Vector3.MoveTowards(transform.position, path[currentPointIndex].position, speed * Time.deltaTime); if (Vector3.Distance(transform.position, path[currentPointIndex].position) < 0.1f) { currentPointIndex++; } } else { IsMoving = false; } } } public void StartMovement() { currentPointIndex = 0; IsMoving = true; } } ``` 注意事项: - 确保路径点按照顺序排列,以保证汽车能正确沿着路径行驶。 - 在Unity编辑器中设置好各个Transform组件的引用,包括起点和所有路径点。 - 根据实际需求调整`spawnInterval`和`speed`值,以适应不同场景下的效果。 ######[AI写代码神器 | 581点数解答 | 2025-01-06 22:07:58]
- Windows环境下C/C++项目开发:完整目录、文件路径及编译脚本设置示例(字节豆包 | 459点数解答 | 2024-11-02 20:38:01)251
- 巧用二分查找:求解塔台超频最小电压实现信号依次传输(字节豆包 | 720点数解答 | 2025-11-26 20:30:18)55
- VS Code 中用 PlantUML 绘制车辆启动、怠速等行驶状态转换 UML 状态图(字节豆包 | 163点数解答 | 2024-08-13 13:57:14)421
- UML状态图揭秘:车辆行驶状态转换全解析(阿里通义 | 828点数解答 | 2024-08-14 23:18:48)442
- 用 UML 状态图呈现车辆启动到停止的状态转换关系(GPT | 574点数解答 | 2024-08-14 23:19:19)384
- 车辆行驶状态全解析:用 UML 状态图看启动、怠速等状态转换关系 (字节豆包 | 236点数解答 | 2024-08-15 22:44:51)288
- C++ 实战:交通工具基类与小汽车类的继承实现及测试(字节豆包 | 391点数解答 | 2024-09-18 16:16:39)276
- Java 实现交通工具类继承:从 Vehicles 到 Car 的完整示例(字节豆包 | 289点数解答 | 2024-09-18 16:16:54)251
- Java 继承实战:交通工具与小汽车类的定义与测试(字节豆包 | 293点数解答 | 2024-09-18 21:36:23)379
- Java实战:交通工具与小汽车类定义及测试全解析(字节豆包 | 290点数解答 | 2024-09-18 21:39:01)345
- Java 实战:交通工具类(Vehicle)及子类小汽车(Car)、卡车(Truck)的继承与实现(GPT | 919点数解答 | 2024-09-20 08:06:42)377
- C++实现交通工具及小汽车类:含代码示例与注意要点(字节豆包 | 378点数解答 | 2024-12-01 22:22:46)231