/// <summary>
/// 攻击判断,在攻击方攻击动画关键帧事件调用该函数,判断是否攻击成功
/// </summary>
/// <param name="attackT">攻击方 Transform</param>
/// <param name="attackDistance">攻击方的攻击距离</param>
/// <param name="attackHp">攻击方的hp</param>
/// <param name="allowAttackLayer">攻击方可以被攻击layer层</param>
/// <param name="enemyT">被攻击方 Transform </param>
/// <param name="enemyHp">被攻击方hp</param>
/// <returns></returns>
public static bool AttackDetermine(Transform attackT, float attackDistance, int attackHp, string allowAttackLayerName, Transform enemyT, int enemyHp)
{
if (enemyT == null || attackT == null)// || enemyT == attackT || enemyHp <= 0 || attackHp <= 0 || LayerMask.LayerToName(enemyT.gameObject.layer) != allowAttackLayerName)
{
Debug.LogError("enemyT == null || attackT == null");
return false;
}
Vector3 dir = enemyT.position - attackT.position; //与敌人的角度面向
float andEnemyAngle = Vector3.Angle(dir, attackT.forward); // 求出attackT指向敌人和attackT指向正前方两向量的夹角,其实就是 正前方和敌人的角度
var attackColleder = enemyT.GetComponentInChildren<Collider>();
var enemyColleder = enemyT.GetComponentInChildren<Collider>();
if (attackColleder == null || enemyColleder == null)
{
Debug.LogError("attackColleder == null || enemyColleder == null");
return false;
}
var start = attackColleder.ClosestPointOnBounds(enemyT.position);
var end = enemyColleder.ClosestPointOnBounds(attackT.position);
var andColliderDis = Vector3.Distance(start, end);
var hight =Mathf.Abs(attackT.position.y - enemyT.position.y) ;
bool isAttackSuccess = enemyT != attackT && attackHp >= 0 && enemyHp >= 0 && hight < 0.7f && andEnemyAngle < 60 && andColliderDis < attackDistance && LayerMask.LayerToName(enemyT.gameObject.layer) == allowAttackLayerName;
Debug.Log("近战攻击判定结果:" + isAttackSuccess + "\n"+
attackT.name + "====攻击====>" + enemyT.name + "\n" +
String.Format("敌人不是自己:{0,37}", (enemyT != attackT)) + "\n" +
String.Format("我的血量:" + attackHp + "\n") +
"敌人当前血量:" + enemyHp + "\n" +
"我正前方和敌人的角度是:" + Math.Round(andEnemyAngle,2) + "度,攻击角度是否符合:" + (andEnemyAngle < 60) + "\n" +
"碰撞器之间距离:" + andColliderDis + "米,攻击距离:" + attackDistance + "米,敌人是否在攻击范围内:" + (andColliderDis < attackDistance) + "\n" +
"与敌人所站位置高度相差:" + hight + "米,"+ ((hight > 0.7f)?"是":"否") + " 超过了0.7f米" + "\n" +
"可以攻击的层:["+allowAttackLayerName+ ":"+ LayerMask.GetMask(allowAttackLayerName) + "],敌人的层:[" + LayerMask.LayerToName(enemyT.gameObject.layer)+":" + enemyT.gameObject.layer +"],结果:"+(LayerMask.LayerToName(enemyT.gameObject.layer) == allowAttackLayerName) + "\n" );
return isAttackSuccess;
}