AS3 Random Range Class

September 26th, 2008

Another simple class that can save some time.

Class:

package {
public class Random {
public static function range(minNum:Number, maxNum:Number, round:Boolean = true) {
if(minNum < 0) {
var posMin = (minNum*-1);
var range = posMin+maxNum;
if(round) { return Math.floor(Math.random() * (range - 1))-posMin; }
else { return Math.random() * (range - 1)-posMin; }
} else {
if(round) { return Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum; }
else { return Math.random() * (maxNum - minNum + 1) + minNum; }
}
}
}
}

Implementation:

import Random;

// range(low:Number, high:Number, round:Boolean = true)
trace(Random.range(10, 15)); // 11
trace(Random.range(-100, 20)); // -56
trace(Random.range(-100, 20, false)); // -32.13413403

One Response to “AS3 Random Range Class”

  1. It did save some time
    Nice to be able to have a look at the code straight away too, thx a bunch