How can I check at what force an object collides with another?
So I want my code to look like this:
function OnCollisionEnter(collision : Collision) {
if( //force is greater than 1) {
print "hit with force";
}
}
My question is what should I write in replace of the “//force is greater than 1” portion.
Thanks.
You can estimate the impact multiplying the relative velocity by the other object’s mass (use a huge mass if the other object has no rigidbody):
function OnCollisionEnter(collision: Collision){
var otherMass: float; // other object's mass
if (collision.rigidbody)
otherMass = collision.rigidbody.mass;
else
otherMass = 1000; // static collider means huge mass
var force = collision.relativeVelocity * otherMass;
if (force > 1){
print("Force = "+force);
}
}
This is not physically correct, but works for many cases. When the collision isn’t frontal, however, the force estimated may be excessive. To handle these cases, the only alternative is to calculate the reaction force from the rigidbody.velocity before and after the collision - take a look at my answer in this question: it creates an OnAfterCollision fake event that calculates and passes the reaction force value as a vector - you can use force.magnitude to compare to some absolute value.
Force is normally a matter of SPEED * MASS, thus you need to use your collision parameter to fetch the RIGIDBODY of the other object (c# code)
Rigidbody myrigidbody = collision.rigidbody;
float myforce = myrigidbody.velocity * myrigidbody.mass;
if (myforce > 1) etc. etc.