判斷周圍是否有敵人的三種模式(轉)

一、只攻擊正前方的單位,向前發射一條射線,攻擊碰到的單位c#

RaycastHit hit;
//range 射線的長度,即攻擊範圍,maskTarget敵方單位的mask,只攻擊敵方單位
if(Physics.Raycast(unit.thisT.position, unit.thisT.forward,out hit, range, maskTarget))
{
    Unit targetTemp=hit.collider.gameObject.GetComponent();
    if(targetTemp!=null &&
    targetTemp.HPAttribute.HP>0)
    {
        target=targetTemp;
        if(attackMode==_AttackMode.StopNAttack)
        {
            if(attackMethod!=_AttackMethod.Melee)
            unit.StopAnimation();
            unit.StopMoving();
        }
    }
}

二、以己方單位爲圓心的某一半徑長度內dom

//返回相交球的全部碰撞體
    Collider[] cols=Physics.OverlapSphere(unit.thisT.position,range, maskTarget);
    //if(cols!=null && cols.Length>0)
    Debug.Log(cols[0]);
    if(cols.Length>0)
    {
        Collider currentCollider=cols[Random.Range(0,cols.Length)];
        Unit targetTemp = currentCollider.gameObject.GetComponent();
        if(targetTemp!=null &&
        targetTemp.HPAttribute.HP>0){
        target=targetTemp;
        if(attackMode==_AttackMode.StopNAttack)
        {
            if(attackMethod!=_AttackMethod.Melee)
            unit.StopAnimation();
            unit.StopMoving();
        }
    }
}

三、以己方單位爲圓心的扇形範圍內ide

Collider[] cols=Physics.OverlapSphere(unit.thisT.position,range, maskTarget);
//if(cols!=null && cols.Length>0)
 Debug.Log(cols[0]);
if(cols.Length>0)
{
    Collider currentCollider=cols[0];
    foreach(Collider col in cols)
    {
        Quaternion targetRot=Quaternion.LookRotation(col.transform.position-unit.thisT.position);
        if(Quaternion.Angle(targetRot, unit.thisT.rotation)
            Unit targetTemp=currentCollider.gameObject.GetComponent();
            if(targetTemp!=null &&
            targetTemp.HPAttribute.HP>0)
        {
            target=targetTemp;
            if(attackMode==_AttackMode.StopNAttack)
            {
                if(attackMethod!=_AttackMethod.Melee)
                    unit.StopAnimation();
                unit.StopMoving();
            }
            break;
        }
    }
}
相關文章
相關標籤/搜索