敌人的自动巡逻脚本
此脚本可实现敌人的自动巡逻,随机方向,随机距离。
public enum EnemyState //枚举不同的状态{NormalState,FightingState,MovingState,RestingState}private NavMeshAgent enemyAgent;private EnemyState state=EnemyState.NormalState;private EnemyState childState = EnemyState.RestingState;public float restTime = 2;//休息时间private float restTimer = 0;//当前休息了多久void Start(){enemyAgent = GetComponent<NavMeshAgent>();//获取寻路组件}// Update is called once per framevoid Update(){if (state==EnemyState.NormalState) {if (childState == EnemyState.RestingState)//如果当前状态为休息状态{restTimer += Time.deltaTime;//休息时间计时if (restTimer > restTime)//判断是否休息够了时间{Vector3 randomPosition= FindRandomPosition();//获取随机目标点enemyAgent.SetDestination(randomPosition);//导航到目标位置childState = EnemyState.MovingState;//状态设为移动状态}} else if (childState==EnemyState.MovingState) //如果当前状态为移动状态{if(enemyAgent.remainingDistance<=0.2f)//如果到达目标位置{restTimer = 0;//休息时间归0childState = EnemyState.RestingState;//回到休息状态}} }}Vector3 FindRandomPosition()//随机移动 {Vector3 randomDir =new Vector3(Random.Range(-1,1f),0,Random.Range(-1,1f));//生成一个随机的方向return transform.position + randomDir.normalized * Random.Range(3,8);//返回一个随机的距离}