- Home /
Applying a force to multiple rigidbodies at once.
Hello all,
I want to script an event where if a first person controller collides with an invisible trigger cube, it applies an AddForce to multiple specified rigidbodies at once, sending them all flying in the direction of the player.
I have the Javascript code working for a single object - the code, attached to the trigger, is below. How would I extend this code to act on multiple rigidbodies at once?
#pragma strict
var target : Collider; // first person controller
var act_on : Rigidbody; // at the moment, a cube
var speed = 10;
function OnTriggerEnter(collision : Collider)
{
if (collision != target) //if the colliding object isn't our object...
{
return; //don't do anything
}
Debug.Log ("Collision");
act_on.rigidbody.AddForce(Camera.main.transform.forward * (speed * -1));
}
Answer by Oana · Jul 02, 2013 at 12:57 PM
Maybe something like this:
#pragma strict
var target : Collider; // first person controller
var act_on : Rigidbody []; // at the moment, a cube
var speed = 10;
function OnTriggerEnter(collision : Collider)
{
if (collision != target) //if the colliding object isn't our object...
{
return; //don't do anything
}
Debug.Log ("Collision");
for (var act:Rigidbody in act_on)
act.AddForce(Camera.main.transform.forward * (speed * -1));
}
thanks, this is great! could this be further developed to work with tags?
Answer by xKroniK13x · Jul 02, 2013 at 02:40 PM
Original code by Oana, edited slightly for this application.
#pragma strict
var target : Collider; // first person controller
var act_on : Rigidbody []; // at the moment, a cube
var speed = 10;
function OnTriggerEnter(collision : Collider) {
if (collision != target) //if the colliding object isn't our object...
{
return; //don't do anything
}
Debug.Log ("Collision");
act_on = GameObject.FindGameObjectsWithTag("TagName"); //Finds all game objects with said tag and assigns them to move
for (var act:Rigidbody in act_on){
act.AddForce(Camera.main.transform.forward * (speed * -1));
}
}
Thanks very much, this is exactly what I needed! I also realised that to fly towards the player I needed to calculate
var direction = playerObject.transform.position - act.transform.position;
act.AddForce(direction * speed);
well on my way now!
Hmm, there seems to be a problem with the code... you're assigning elements of act as GameObjects, but the array is declared as Rigidbody at the start. Getting lots of errors that Unity can't convert one to the other?
You're absolutely right, the var act_on : Rigidbody [];
line should read: var act_on : GameObject [];
Hope this solves it!
Your answer
Follow this Question
Related Questions
Collisions when pushing object 1 Answer
Physics optimization 3 Answers
Colliders going through walls 1 Answer
seeking collision scenario solution : falling anvil vs. player 0 Answers