Search Unity

Sounds on Collision

Discussion in 'Scripting' started by tsphillips, Jan 16, 2006.

  1. tsphillips

    tsphillips

    Joined:
    Jan 9, 2006
    Posts:
    359
    Just a tip on making sounds when things collide...

    The physics demo included with Unity has a script that looks like this:

    Code (csharp):
    1.  
    2. function OnCollisionEnter (col : Collision) {
    3.     if (col.relativeVelocity.magnitude > 10) {
    4.         if (audio  !audio.isPlaying) {
    5.             audio.Play ();
    6.         }
    7.     }
    8. }
    9.  
    This script, along with an audio clip, is attached to an object. The effect is that the object will emit a sound when it collides with something. Sometimes. I went nuts making a bouncing ball demo with many balls; the net sound output seemed very much out of sync with what was happening on the screen. The solution was to modify the constant 10.

    I would recommend changing this script to the following:

    Code (csharp):
    1.  
    2. var threshold = 10;
    3.  
    4. function OnCollisionEnter (col : Collision) {
    5.     if (col.relativeVelocity.magnitude > threshold) {
    6.         if (audio  !audio.isPlaying) {
    7.             audio.Play ();
    8.         }
    9.     }
    10. }
    11.  
    After this script is attached to the object, a "threshold" variable with a default value of 10 will appear in the object's inspector. Lower numbers will cause the sound to play during less energetic collisions. Zero (0) is a valid threshold.

    I have also played with a line like the following:
    Code (csharp):
    1.  
    2. audio.volume = col.relativeVelocity.magnitude;
    3.  
    The problem with this is that there is no clear scale for audio volume vs. rolloff value vs. collision magnitude, so the quieter sounds tend to just disappear. I'm not sure how much effort would be required to callibrate all these values.

    Tom