Unity3d 攻擊判斷 通過攻擊動畫關鍵幀加上角度和距離判定

    /// <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;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章