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!