- Home /
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?
Answer by aldonaletto · Apr 05, 2012 at 08:58 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613065948im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Keep a certain distance between two RigidBodies 2 Answers
Handling colliders on hundreds of asteroids (not procedural asteroids) ...URGENT 3 Answers
Calculate where an object is going to land 0 Answers
Restrict two objects from getting too close. 1 Answer
Rigidbodies won't collide if mass difference is too high 0 Answers