x


Simple way to get all objects (rigidbodys) around x distance from the player

Hello everyone,

I want to make a script that drags all rigidbodys which are for example 0-10 distance away from the player. Any good idea how to do that?

more ▼

asked Apr 05 '12 at 08:13 PM

Ebil gravatar image

Ebil
135 17 22 24

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

The easiest way is to use Physics.OverlapSphere: it creates an array with all colliders whose bounding boxes touch the given sphere (see a good example here). The script below kicks out any rigidbody inside rad radius (add script to the player):

var dragSpeed: float = 2.0; // initial speed that the rigidbody will be thrown away

function KickRigidbodies(rad: float) {
    var center: Vector3 = transform.position;
    // get all colliders touching the sphere radius rad
    var colliders: Collider[] = Physics.OverlapSphere(center, rad);
    for (var col: Collider in colliders) {
        if (col.rigidbody && !col.rigidbody.isKinematic){ // if it's a non kinematic rigidbody...
            var dir = col.transform.position - center; // dir = player->object
            col.rigidbody.velocity = dir.normalized * dragSpeed; // kick it out
        }
    }
}

Just call the function KickRigidbodies(r) to kick out at dragSpeed all rigidbodies that touch the sphere centered at the player and with radius r. The speed will be the same, no matter how massive the rigidbody is. If you want to take mass into account, use rigidbody.AddForce instead of setting rigidbody.velocity.

more ▼

answered Apr 05 '12 at 08:58 PM

aldonaletto gravatar image

aldonaletto
41.4k 16 42 197

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1868
x1787
x354
x155

asked: Apr 05 '12 at 08:13 PM

Seen: 439 times

Last Updated: Apr 05 '12 at 08:58 PM