其实原理很简单,就是使用组件“Nav Mesh Agent”,当到达目的地的时候设置新的目的地,具体代码如下。
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour
{
NavMeshAgent nav;
Vector3 originalPosition;
Vector3 newPosition = Vector3.zero;
Vector3 currentDestination = Vector3.zero;
float waitTime = 3f;
bool canMoving = true; //控制物体是否能够移动
void Start () {
nav = GetComponent <NavMeshAgent> ();
originalPosition = transform.position; //拿到物体初始位置
float x = Random.Range (-10, 10);
float z = Random.Range (-10, 10);
newPosition = new Vector3 (originalPosition.x + x, originalPosition.y, originalPosition.z + z); //拿到物体随机得到的另一个位置
currentDestination = newPosition;
}
void Update ()
{
if (canMoving) {
nav.SetDestination (currentDestination);
if (nav.remainingDistance < 0.5f) { //到达目的地后暂停3s,然后切换目的地,达到来回走动的效果
canMoving = false;
StartCoroutine(delayCoroutine()); //停留3s再返回
}
}
}
IEnumerator delayCoroutine() {
if (Vector3.Equals (currentDestination, newPosition)) {
currentDestination = originalPosition;
} else {
currentDestination = newPosition;
}
yield return new WaitForSeconds(waitTime);
canMoving = true;
}
}
版权声明:本文为u011601165原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。