- Home /
Question by
termsofuse_bob · Sep 02, 2015 at 09:35 AM ·
c#2d-platformer2d-physics
[2D] Add force to all colliders within a certain radius
Hello! I am making a 2D game and after a few days of testing, I am unsure how to add force to all colliders within a certain radius. As seen as this is a 2D game, AddExplosionForce cannot be used (maybe it can and I am just missing something).
Comment
Answer by Ermiq · Aug 16, 2018 at 12:04 AM
Maybe use Physics2D.CircleCast
or Physics2D.OverlapCircle
to get array of colliders:
Vector2 originOfExplode;
float radius;
float forceMultiplier; // force of the explosion
public void Explosion ()
{
Collider2D[] colliders = Physics.OverlapCircleAll (originOfExplode, radius);
foreach (Collider2D col in colliders)
{
// the force will be a vector with a direction from origin to collider's position and with a length of 'forceMultiplier'
Vector2 force = (col.transform.position - originOfExplode) * forceMultiplier;
Rigidbody rb = col.transform.GetComponent<Rigidbody> ();
rb.AddForce (force);
}
}
Your answer
Follow this Question
Related Questions
HOLD THE JUMP BUTTON TO JUMP HIGHER 0 Answers
Transform.position assign attempt not valid, and position is infinity on an object? 1 Answer
How to detect if player is moving. 1 Answer
Jump Code Not Working (2D C#) 2 Answers
How to check if my enemy hits the ground at a certain velocity then add explosive force. 1 Answer