using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BuildSystem { public enum Dir { none,up,down,left,right } public class Car : MonoBehaviour { private Vector2Int now; public bool isCanMove = true; public bool isMoveEnd = true; public List passList = new List(); public Queue moveRoad = new Queue();//移动路径 private void Start() { now = new Vector2Int(0, 2); moveRoad.Enqueue(RandomFindRoad(BuildSystemManager.Instance.gridMap[now.x][now.y])); moveRoad.Enqueue(RandomFindRoad(moveRoad.ToArray()[moveRoad.Count - 1])); StartCoroutine(StartMove()); } private void Update() { if (moveRoad.Count < 3) { moveRoad.Enqueue(RandomFindRoad(moveRoad.ToArray()[moveRoad.Count - 1])); } } /// /// 随机寻找下一个路径 /// /// Grid RandomFindRoad(Grid grid) { passList.Add(grid); Grid obj; while (true) { int rand = Random.Range(0, BuildSystemManager.Instance.gridMap[grid.x][grid.z].ground.Count); obj = BuildSystemManager.Instance.gridMap[grid.x][grid.z].ground[rand]; if (!passList.Contains(obj)) { break; } } return obj; } /// /// 开启车辆移动 /// /// IEnumerator StartMove() { while (moveRoad.Count != 0) { yield return new WaitUntil(() => { return isMoveEnd;}); isMoveEnd = false; Debug.Log(moveRoad); Grid grid = moveRoad.Dequeue(); StartCoroutine(Move(grid)); } } /// /// 车辆移动到目的点 /// /// 下一个点的目标 /// IEnumerator Move(Grid nextGird) { Grid nextnextGrid = moveRoad.ToArray()[moveRoad.Count - 1]; List roadPos = nextGird.placeObject.GetComponent().GetRoad(BuildSystemManager.Instance.gridMap[now.x][now.y], nextGird, nextnextGrid); isMoveEnd = false; for (int i = 0; i < roadPos.Count;) { while (true) { yield return new WaitUntil(() => { return isCanMove; }); yield return new WaitForEndOfFrame(); Vector3 dir = (roadPos[i].position - transform.position).normalized; transform.position += dir * Time.deltaTime * 10; Quaternion quaternion = Quaternion.LookRotation(roadPos[i].position - transform.position); transform.rotation = quaternion; if (Vector3.Distance(transform.position, roadPos[i].position) <= 0.5f) { Debug.Log("到达"); i++; break; } } } now = new Vector2Int(nextGird.x, nextGird.z); Debug.Log("结束"); isMoveEnd = true; } } }