首先在场景中创建几个巡逻的点,将玩家和敌人的Tag设置为相应的Tag
其中enemy的组件如下
在Enemy脚本中代码如下
public class Enemy : MonoBehaviour
{
public float PatrolSpeed = 3f;
public float PatrolWaitTime = 1f;
public Transform PatrolWayPoints;
private NavMeshAgent agent;
private float PatrolTimer = 0f;
private int wayPointsIndex = 0;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
Patrolling();
}
///
/// 巡逻函数
///
void Patrolling()
{
agent.isStopped = false;//首先将运动状态设置为运动
agent.speed = PatrolSpeed;//设置巡逻速度
if (agent.remainingDistance < agent.stoppingDistance)//如果已经到达目标点
{
PatrolTimer += Time.deltaTime;
if (PatrolTimer > PatrolWaitTime)
{
if (wayPointsIndex == PatrolWayPoints.childCount - 1)
wayPointsIndex = 0;
else
wayPointsIndex++;
PatrolTimer = 0;
}
}
else
PatrolTimer = 0;
agent.destination = PatrolWayPoints.GetChild(wayPointsIndex).position;
}
}