unity_小功能实现(敌人巡逻功能)

利用NavMeshAgent控制敌人巡逻,即敌人在一组位置间循环巡逻。

首先我们要知道NavMeshAgent中有两个方法:1.锁定当前巡逻的某一目标位置,即navMeshAgent.destination

2.到达目标位置停止巡逻(休息一定时间继续巡逻),即navMeshAgent.Stop();

代码实现如下:

usingUnityEngine;

usingSystem.Collections;

using UnityEngine.AI;

public class EnemyMoveAI : MonoBehaviour {

public Transform[] directPoints; //0-3

privateint index = 0;

    public float patroTime = 3f;//到达某一点停止等待时间

    private float timer = 0;//计时器

privateNavMeshAgentnavMeshAgent;

void Awake()

    {

navMeshAgent = GetComponent<NavMeshAgent>();

navMeshAgent.destination = directPoints[index].position;

    }

void Update()

    {  

if (navMeshAgent.remainingDistance< 0.5f)

        {

timer += Time.deltaTime;

if (timer==patroTime)

            {

index++;

                index %= 4;//在4个点之间循环巡逻

timer = 0;

navMeshAgent.destination = directPoints[index].position;

            }

        }

    }

}

注意:

1.为了保证敌人能在该组点内循环巡逻(而不是只巡逻一圈),采用取余的方式获得点数组的下标。

2.没有使用navMeshAgent.Stop();原因是,如果使用了则到达一个巡逻点后敌人将不会再向新的目标点移动。

原文地址:https://www.cnblogs.com/shirln/p/9105556.html