I’m putting the finishing touches on a Unity port of my iOS game Air Hockey. I’m using collision.relativeVelocity to vary the volume of a sound played when two objects in my game hit each other. I’m having a problem when one of those objects is at rest.
I have a script attached to one object (the puck in the game). When that object is stationary and hit by something else, the collision.relativeVelocity.magnitude is 0. The math behind the relativeVelocity calculation isn’t listed in the docs. If that calculation is made before any update to the rigidbodies’ velocities is made (which is where I really want it), then even if one body is at rest, the other body’s velocity should still show up in the relativeVelocity…but it doesn’t.
You can’t have a collision when there’s 0 relative velocity, right? I’ve tried this in Unity 3.5.6 and 4.x and get the same result in both places.
Here’s my code from my puck object:
void OnCollisionEnter (Collision collision) {
if(collision.collider.CompareTag("mallet")) {
//PlaySound(<what sound>, <transform location to play sound>, <volume>)
PlaySound(collisionSound1,collision.collider.transform,Mathf.Clamp(collision.relativeVelocity.magnitude * 0.0002f,0.05f,1.0f));
//write the relative velocity magnitude out...why is it 0 when this object is at rest?
Debug.Log("collision.relativeVelocity.magnitude: " + collision.relativeVelocity.magnitude);
}
}
So, is collision.relativeVelocity behaving by Unity’s design? If it is, then 1) why is it designed this way and 2) is there something else that I should be using instead?
Thanks!