代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AIEnemy : MonoBehaviour
{
private NavMeshAgent nav;
public GameObject targetPos;
public bool isNavGuide = true;
public float catchDis = 20.0f;
public int enemySpeed = 15;
public AIVehicle aIVehicle;
private Rigidbody rig;
void Start()
{
nav = this.transform.GetComponent<NavMeshAgent>();
targetPos = GameObject.FindGameObjectWithTag("Player");
aIVehicle = targetPos.GetComponent<AIVehicle>();
}
void Update()
{
if (isNavGuide != false && aIVehicle.currentLap != 1)
{
CalEnemyToPlayer();
}
}
public void CalEnemyToPlayer()
{
try
{
nav.enabled = true;
nav.speed = enemySpeed;
transform.LookAt(targetPos.transform);
nav.SetDestination(targetPos.transform.position);
float dis = Vector3.Distance(this.transform.position, targetPos.transform.position);
//float dis = nav.remainingDistance;
if (dis < catchDis+10)
{
aIVehicle.isGameOver = true;
//nav.acceleration = -(nav.speed/5.0f);
isNavGuide = false;
StartCoroutine(StopNav());
nav.speed = Mathf.MoveTowards(nav.speed, 0, 1.0f);
Debug.Log("Game Over...");
}
}
catch (System.Exception e)
{
Debug.Log("The Err is:" + e);
}
}
IEnumerator StopNav()
{
yield return new WaitForSeconds(1.1f);
nav.isStopped = true;
nav.enabled = false;
Debug.Log("Stop Nav...");
}
}