Player also recieving damage from AOE

rpg_s03_create_an_area_of_effect_ability

#1

Hey guys,

So I noticed that the way this is done in the course is by looking for IDamageables, which causes the Player to also receive damage as it also inherits from IDamageable.

The way I approached it is by making use of LayerMask in the SphereCastAll params.

public void Use(AbilityParams abilityParams)

     {
        int layerMask = 1 << 9; // 9 is enemy layer 
        RaycastHit[] enemiesInAreaOfEffect;
        float damageToDeal = areaOfEffectConfig.GetDamagePerTarget();  

        //Is casting Ray here as well as in CameraRaycaster an issue?
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        enemiesInAreaOfEffect =  Physics.SphereCastAll(ray, areaOfEffectConfig.GetRadius(), areaOfEffectConfig.GetRadius(), layerMask);
        foreach (RaycastHit enemyHit in enemiesInAreaOfEffect)
        {
            var damageable = enemyHit.collider.gameObject.GetComponent<IDamageable>();
            if (damageable!= null )  
            {
                print(damageable);
                print("layermask " + layerMask);
                damageable.TakeDamage(damageToDeal);
            }
        }

Any thoughts on this would be appreciated :slight_smile:


#2

Hi, I did not want to mess with the layer mask (no magic numbers!) and only called the TakeDamage function when the hit.gameObject is different from the player game object:

public void Use(AbilityParams abilityParams){
            RaycastHit[] raycastHits = Physics.SphereCastAll(
                transform.position, config.GetRadius(), Vector3.up, config.GetRadius()
            );

            foreach(RaycastHit hit in raycastHits){
                if (hit.collider.gameObject != gameObject) {
                    IDamagable damagable = hit.collider.gameObject.GetComponent<IDamagable>();
                    if (damagable != null) {
                        float damageToDeal = config.GetDamageToEachTarget() + abilityParams.baseDamage;
                        damagable.TakeDamage(damageToDeal);
                    }
                }
            }
        }

I wanted to keep the number of the enemies layer defined only inside the CameraRayCasting class.

Cheers!