Actionscript 3 random
This article originated mainly from my personal needs. I often need to generate a random value in AS 3.0, but not always remember exactly how to generate specific random number. So I gathered some useful lines of code that I personaly use. Hope you find them useful :-)
- random number between 0 and 1
var myNum:Number = Math.random(); trace(myNum); // gives something like 0.4654723424464464
- random number between 0 and 5
var myNum:Number = Math.random()*5; trace(myNum); // gives same long numbers as example abowe but between 0 and 5
- If you need an integer from random number.
var myNum:Number = Math.floor(Math.random()*5); trace(myNum); // gives you random between 0 and 5 rounding decimal numbers down var myNum:Number = Math.ceil(Math.random()*5); trace(myNum); // gives you random between 0 and 5 rounding decimal numbers up var myNum:Number = Math.round(Math.random()*5); trace(myNum); // gives you random between 0 and 5 rounding decimal numbers up or down
- And if you need to start from number other than 0
var myNum:Number = Math.ceil(Math.random()*15) + 5; trace(myNum); // gives you random number between 5 and 20;
- If you need to specify minimum and maximum value
var minLimit:uint = -5; var maxLimit:uint = 20; var range:uint = maxLimit - minLimit; varmy Num:Number = Math.ceil(Math.random()*range) + minLimit; trace(myNum); //gives you random numbers from -5 to 20