Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

collision.relativeVelocity

Discussion in 'Scripting' started by Groucho, Feb 24, 2013.

  1. Groucho

    Groucho

    Joined:
    Dec 24, 2009
    Posts:
    73
    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:
    Code (csharp):
    1. void OnCollisionEnter (Collision collision) {
    2.            
    3.     if(collision.collider.CompareTag("mallet")) {
    4.  
    5.         //PlaySound(<what sound>, <transform location to play sound>, <volume>)
    6.         PlaySound(collisionSound1,collision.collider.transform,Mathf.Clamp(collision.relativeVelocity.magnitude * 0.0002f,0.05f,1.0f));
    7.  
    8.         //write the relative velocity magnitude out...why is it 0 when this object is at rest?
    9.         Debug.Log("collision.relativeVelocity.magnitude: " + collision.relativeVelocity.magnitude);
    10.     }
    11. }
    12.  
    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!
     
  2. Stankiem

    Stankiem

    Joined:
    Dec 4, 2013
    Posts:
    115
    Also wondering this, relativevelocity doesn't seem to function as described at all. It seems to only account for the velocity of a single object.