Unity3d – javascript – normalize a number so that it falls between a range between 0 and 1

mathnormalizerangeunity3dunityscript

I have an experiment where my program picks up audio from my speakers (in decibels…sort of). The range is usually between about 0 and 20. I want to take that value and map it to a range between 0 and 1 so that I can scale an item in proportion to the volume coming through the speakers. So if the audio was 20 db, the scale would be 1. If the audio was 0 dB, the scale would be 0. How do I do this? I'm using Unity3D, if that gives anyone an idea for a helper function.

Best Answer

Divide it by 20, if that is truly the maximum.

var scale = function(db) {
   return db/20;
}

or

    var scale = function(db) {
     if (db > 0)
         {

         return db/20;

         }
     else if (db < 0)
        {

        return "db is out of range"; # or do something

        }
     else 
        {
      return "something else";

        }

  }