赞
踩
此脚本可实现敌人的自动巡逻,随机方向,随机距离。
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 frame void 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;//休息时间归0 childState = 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);//返回一个随机的距离 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。