酷代码 AI
菜单
服务商

写一个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`值,以适应不同场景下的效果。 [2025-01-06 22:07:58 | AI写代码神器 | 581点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]