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.

138 lines
3.9 KiB

3 years ago
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
/// <summary>
/// 车辆管理类
/// 功能:车辆生成
/// 车辆AI
///
/// </summary>
public class CarSys : MonoBehaviour
{
//计时器
private float timer = 0f;
//车辆生成间隔
public float bornTime = 10;
//车辆种类列表
public GameObject[] carList;
//移动点列表
private Dictionary<string, Transform> MoveList = new Dictionary<string, Transform>();
//生成点列表
private Dictionary<string, Transform> BornList = new Dictionary<string, Transform>();
public void Init()
{
CheckBornoint();
CheckMovePoint();
}
//检索移动点
public void CheckBornoint()
{
GameObject[] bornPoints = GameObject.FindGameObjectsWithTag("BornPoint");
for (int i = 0; i < bornPoints.Length; i++)
{
BornList.Add(bornPoints[i].name, bornPoints[i].transform);
}
}
//检索移动点
public void CheckMovePoint()
{
GameObject[] moveObjs = GameObject.FindGameObjectsWithTag("MoveList");
for (int i = 0; i < moveObjs.Length; i++)
{
MoveList.Add(moveObjs[i].name, moveObjs[i].transform);
}
}
//车辆AI移动函数
public IEnumerator CarMove(string lineName,NavMeshAgent agent)
{
if (lineName != "" && agent != null)
{
Transform moveListParent = null;
MoveList.TryGetValue(lineName,out moveListParent);
if (moveListParent != null)
{
Transform[] moveList=new Transform[moveListParent.childCount];
//遍历移动列表
for (int i = 0; i < moveListParent.childCount; i++)
{
moveList[i] = moveListParent.GetChild(i);
if (moveList[i] != null)
{
//向移动列表支点移动
agent.speed = 20;
agent.SetDestination(moveList[i].position);
//携程检测距离与路况
while (true)
{
//*********************//
yield return new WaitForEndOfFrame();
float distance = Vector3.Distance(agent.transform.position, moveList[i].position);
if(distance <= 40f)
{
agent.speed = 10;
}
if (distance <= 0.4f) {
agent.velocity= Vector3.zero;
break;
}
}
}
}
//回收车辆
Destroy(agent.gameObject);
}
}
}
//汽车生成函数
public void CreatCar(float time)
{
//计时
timer += Time.deltaTime;
if (timer < time)
{
return;
}
else
{
timer = 0;
}
//随机获取出生点
Transform parent = null;
int pointIndex= Random.Range(1, BornList.Count);
BornList.TryGetValue("0" + pointIndex.ToString(),out parent);
//随机创建车辆种类
if (parent != null)
{
int carIndex = Random.Range(0, carList.Length-1);
GameObject car = GameObject.Instantiate(carList[carIndex],parent.position,Quaternion.identity,parent);
car.transform.localEulerAngles = parent.localEulerAngles;
//执行寻路AI
NavMeshAgent agent = car.GetComponent<NavMeshAgent>();
if (agent != null)
{
StartCoroutine(CarMove(parent.name,agent));
}
}
}
}