You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
3.4 KiB
103 lines
3.4 KiB
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<Grid> passList = new List<Grid>();
|
|
public Queue<Grid> moveRoad = new Queue<Grid>();//移动路径
|
|
|
|
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]));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 随机寻找下一个路径
|
|
/// </summary>
|
|
/// <param name="grid"></param>
|
|
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;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 开启车辆移动
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
IEnumerator StartMove() {
|
|
while (moveRoad.Count != 0) {
|
|
yield return new WaitUntil(() => { return isMoveEnd;});
|
|
isMoveEnd = false;
|
|
Debug.Log(moveRoad);
|
|
Grid grid = moveRoad.Dequeue();
|
|
StartCoroutine(Move(grid));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 车辆移动到目的点
|
|
/// </summary>
|
|
/// <param name="nextGird">下一个点的目标</param>
|
|
/// <returns></returns>
|
|
IEnumerator Move(Grid nextGird) {
|
|
Grid nextnextGrid = moveRoad.ToArray()[moveRoad.Count - 1];
|
|
List<Transform> roadPos = nextGird.placeObject.GetComponent<RoadInfo>().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;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
}
|