2D Explosion

Hey there,
I want to write a simple code for a 2D explosion (Similar to its 3D counterpart, the AddExplosionForce).

My logic has been to look for all the 2D colliders around the explosion area, and apply a directional force on those colliders based on their distance from the center of the explosion.
However, when I tried to implement this, it didn’t work at all. What gives?

This is my code. For reference, Coll.contacts[0].point is where I want to create the source of the explosion:

Collider2D[ ] colliders = Physics2D.OverlapCircleAll(Coll.contacts[0].point, 10f);
foreach (Collider2D hit in colliders)
{
Rigidbody2D rb = hit.GetComponent<Rigidbody2D>();
float Force = 4f;
rb.AddForce(new Vector2(Force * (hit.transform.position.x - Coll.contacts[0].point.x),Force * (hit.transform.position.y - Coll.contacts[0].point.y)));
}

Before anyone points this out - I am fully aware that the magnitude of the force applied is inverse to what it should be (Currently, the further the object is away from the explosion’s center, the MORE force is applied). I’ll get to it after I figure out why this isn’t working.

I would love to hear any ideas as to why this isn’t working. Thanks in advance!

SOLUTION FOUND
So it turns out that, as always, a small mistake leads to a big problem. Thing is, some of the objects the OverlapCircleAll gets DO NOT have a Collider2D component. This meant that as soon as the foreach loop got to one of them, and couldn’t apply the force to it (Because it didn’t exist), it would stop the entire function, and none of the objects that do have Collider2D components got pushed.

Basically, I just added a if (rb != null) clause before my AddForce, and everything worked out :slight_smile:

1 Like