- Home /
Gather objects in one point
Hello! Is it possible to gather rigidbodies in one point, so they move to each other and meet in point, average for all of them. Just like magnets... I am trying different ways, but still can't get it.
Searching forums, I found a nice workable code for magnet-like effect, but it gather all objects around one (for which this code is applied). So it's like a "magnetic bomb". Not what I need exactly... Anyway, here is it:
var blastForce = 0;
var blastRadius = 10;
var implode = true;
function FixedUpdate () {
var things : Collider[] = Physics.OverlapSphere(transform.position, blastRadius);
for (i=0; i<things.length; i++){
if (things[i].attachedRigidbody && things[i].attachedRigidbody != rigidbody){
var offset : Vector3 = (transform.position - things[i].transform.position);
things[i].attachedRigidbody.AddForce(offset/offset.magnitude * -blastForce);
}
}
}
function Update() {
var key1 = Input.GetKey("1");
var key2 = Input.GetKey("2");
if (key1 && implode){
implode = false;
blastForce = -100;
}
if (key2 && !implode){
implode = true;
blastForce = 50;
}
}
Thank you for answering!
Answer by czebrose · Jun 26, 2012 at 06:17 PM
Couldn't you just average the positions of all the points and then apply a force on all the objects towards that point?
something like this:
float blastForce = 5.0f;
Vector3 total = Vector3.zero;
for(thing in things)
{
total += thing.transform.position;
}
Vector3 center = total/things.length;
for(thing in things)
{
thing.attachedRigidbody.AddForce((center - thing.transform.position)*blastForce);
}
I think that'd do it.
czebrose, thank you for answering, but eeh... I am afraid that don't really understand how to use this code. I guess it should be a little bit changed for javascript?
I adapted it like this:
var blastForce : float = 5.0f;
var total : Vector3 = Vector3.zero;
var blastRadius = 10;
function Update() {
var things : Collider[] = Physics.OverlapSphere(transform.position, blastRadius);
for(thing in things)
{
total += thing.transform.position;
}
var center : Vector3 = total/things.length;
for(thing in things)
{
thing.attachedRigidbody.AddForce((center - thing.transform.position)*blastForce);
}
}
but nothing works..
I just tried this with a few boxes and it sort of worked. The boxes ended up falling to oblivion, so you should probably add a stop condition.
That aside, have you tried increasing the size of the blastRadius to say 1000? and do all of your objects have colliders and rigidbodies?
Sorry for answering so late! Yes, I tried that, after your post, but still nothing! $$anonymous$$aybe I missed something? $$anonymous$$aybe some special tags to these rigidbodies?..
Your answer
Follow this Question
Related Questions
Move Objects in beginning of scene 1 Answer
Magnetic object to make coins move to object 2 Answers
Objects automatically move toward another object 1 Answer
Changes not reflected in play mode 1 Answer