// this one-liner is good to know:
// Math.max(minValue, Math.min(maxValue, valueToClamp));
// wrapped in a function it looks like this:
const MIN:Number = 0;
const MAX:Number = 100;
function clamp(val:Number, min:Number = MIN, max:Number = MAX){
return Math.max(min, Math.min(max, val))
}
for (var i:int = 0; i<1000; i++){
var val:Number = Math.random()*1000 - 500;
// clamp the above random value between -100 and +100
trace(clamp(val, -100, 100));
}
Although I show a function implementation above, I use this technique inline a good deal. If there is some value that I need to clamp I’ll often just “max min it”:
var val:Number = Math.random()*1000; // clamp it - 0-100 trace(Math.max(0, Math.min(100, val));
dude, i love you, thanks!