Search Unity

Question Explosion : Prevent protected object within effect zone to be damaged

Discussion in 'Physics' started by MysteriousAnonym, Jan 21, 2021.

  1. MysteriousAnonym

    MysteriousAnonym

    Joined:
    Jan 5, 2020
    Posts:
    3
    Hi,
    I'm new to unity and i try to improve my grenade prototype.

    Right now, the script apply some force to rigidbody within the blast range of the grenade :
    Code (CSharp):
    1. Collider[] collidersToDestroy = Physics.OverlapSphere(transform.position, blastRadius);
    2.         foreach(Collider nearbyObject in collidersToDestroy)
    3.         {
    4.  
    5.             Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
    6.  
    7.             if (rb != null)
    8.             {
    9.                    rb.AddExplosionForce(force, transform.position, blastRadius);
    10.             }
    11.  
    12.         }
    But i want to apply this explosionforce only to objects directly exposed to the blast. Any object behind an other object (ex. a wall) must be protected.

    so what is the method ? I've tried with raycast but rays pass through objects so it's not working.

    Thank you.
     
  2. ramsey05

    ramsey05

    Joined:
    Jan 18, 2020
    Posts:
    25
    ı can help u
     
  3. ramsey05

    ramsey05

    Joined:
    Jan 18, 2020
    Posts:
    25
    foreach (var obj in FindObjectsOfType(typeof(GameObject)) as GameObject[])
    {

    //if u want to find a named object put the code here
    if (obj.name == "obje")
    {
    }
    //if u want to find a layered object put the code here
    if(obj.layer == 1)
    {
    }
    //if u dont want to find objects with layer or name u can delete ifs above from this text

    if (Vector3.Distance(transform.position, obj.transform.position) <= blastRadius)
    {
    if(obj.gameObject.GetComponent<Rigidbody>() != null)
    {
    obj.gameObject.GetComponent<Rigidbody>().AddExplosionForce(force, transform.position, blastRadius);
    }
    }

    try this
    if it wont work tell me or it gives an error again tell me ok
    (sorry for my english)
     
  4. MysteriousAnonym

    MysteriousAnonym

    Joined:
    Jan 5, 2020
    Posts:
    3
    Thanks,

    Your code work but is acting like mine, all objects inside the blast radius is affected by the explosion force. Or i miss something...
     
  5. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
  6. ramsey05

    ramsey05

    Joined:
    Jan 18, 2020
    Posts:
    25
    u can divide the explosion force that u applied to objects to distance beetween explosion and
    objects
     
  7. ramsey05

    ramsey05

    Joined:
    Jan 18, 2020
    Posts:
    25
    then when u divide it u can increase ur blast radius much more when u do that in theori it will act like an gernade