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?
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?
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.