怪物的近战和远程攻击方式脚本:
public enum Type { Melee, Range, Boss }//设置敌人的类型 {近程怪,远程怪,BOSS}
public Type enemyType;
public Transform target;//获取要攻击的对象
public BoxCollider meleeArea;//盒碰撞器,可以设置触发机制
public GameObject bullet;//远程怪使用攻击的物体
protected Rigidbody _rigidbody;//刚体组件
protected NavMeshAgent _navMeshAgent;//导航网络代理组件
protected Animator _animator;//动画组件
protected Health _health;//敌人状态脚本
private float _targetRadius;//半径
private float _targetRange;//范围
private bool _isChase;//是否在寻找玩家
private bool _isAttack;//是否攻击
private void Awake()
{
_rigidbody = GetComponent
_navMeshAgent = GetComponent
_animator = GetComponentInChildren
_health = GetComponent
if (enemyType != Type.Boss)
{
Invoke(nameof(ChaseStart), time: 2);//执行怪寻找玩家
}
}
public void ChaseStart()//敌人寻找玩家
{
_isChase = true;
if (_animator)
{
_animator.SetBool(name: "isWalk", value: true);//调用怪物移动动画
}
}
private void FreeVelocity()
{
_rigidbody.velocity = Vector3.zero;//速度为0
_rigidbody.angularVelocity = Vector3.zero;//角速度为0
}
private void Update()
{
if (_navMeshAgent.enabled && !_health.isDead && enemyType != Type.Boss)//寻路条件
{
_navMeshAgent.SetDestination(target.position);
_navMeshAgent.isStopped = !_isChase;
}
}
private void FixedUpdate()
{
if (_isChase)
{
FreeVelocity();
}
if(enemyType != Type.Boss)//不是BOSS类型调用怪到玩家距离的扫描方法
{
Targeting();
}
}
private void Targeting()//怪到玩家距离扫描
{
if(enemyType == Type.Melee)
{
_targetRadius = 0.5f;
_targetRange = 2f;
}
else if(enemyType == Type.Range)
{
_targetRadius = 0.5f;
_targetRange = 10f;
}
RaycastHit[] hits = Physics.SphereCastAll(origin: transform.position, _targetRadius, direction: transform.forward,maxDistance: _targetRange, LayerMask.GetMask(layerNames: "Player"));//设置怪攻击时对准玩家
if(hits.Length > 0 && !_isAttack)//
{
StartCoroutine(routine: Attack());//调用携程进行攻击
}
}
IEnumerator Attack()//敌人攻击逻辑
{
isChase = false;//关闭寻找
_isAttack = true;//打开攻击
_animator.SetBool(name: "isAttack", value: true);//调用攻击动画
if(enemyType == Type.Melee)//近程
{
yield return new WaitForSeconds(0.2f);
meleeArea.enabled = true;//打开碰撞盒检测
yield return new WaitForSeconds(1f);
meleeArea.enabled = false;//关闭碰撞盒检测
yield return new WaitForSeconds(1f);
}
else if(enemyType == Type.Range)//远程
{
yield return new WaitForSeconds(0.5f);
GameObject InstantBullet = Instantiate(bullet, transform.position, transform.rotation);//生成
Rigidbody rigidbodyBullet = InstantBullet.GetComponent
rigidbodyBullet.velocity = transform.forward * 20f;//向前发射物体
yield return new WaitForSeconds(2f);
}
_isChase = true;
_isAttack = false;
_animator.SetBool(name: "isAttack", value: false);//关闭攻击动画
}