2
\$\begingroup\$

I am currently trying to make all other objects push away from the player when the player explodes. It currently works, but it pushes close objects a little and far objects very far. What I want is for close objects to get pushed back more than far objects. Here is the current code:

function explode () {
var all_rigidbodies = FindObjectsOfType(Rigidbody2D);

for (var r : Rigidbody2D in all_rigidbodies) {
    if (Vector2.Distance(r.transform.position, transform.position) < 6 && r.tag != "Player") {
        var px : float = r.transform.position.x - transform.position.x;
        var py : float = r.transform.position.y - transform.position.y;

        r.AddForce((Vector2(px, py) * 200), ForceMode2D.Force);             
    }
}

Any ideas on how to inverse the vector or force, or better ways to achieve 2D explosions?

EDIT: Ended up just normalizing force so its all the same knockback

\$\endgroup\$
2
\$\begingroup\$

I think if you change the last line to this it should work.

r.AddForce(Vector2(px, py).normalized * EXPLOSION_FORCE / Vector2.Distance(r.transform.position, transform.position));

normalize sets the vector to be length 1, then you multiply by some force and divide by the distance, so the further away it is, the less force is given.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.