Friday, July 2, 2010

Returning random numbers using Actionscript 3

Generating random numbers is often needed when developing a game or an application. That was very simple to do in AS2 with the built-in random() function, which returns a random number ranged from 0 to the entered number. In AS3, it's a little more complicated. There is only one built-in function for that, Math.random(), which returns a random number n, where 0 <= n < 1. Let's create a function that will simplify the randomizing process for us (to make it work like in AS2):



function rand(a:Number):Number{
 return(Math.round(Math.random()*a))
 }

Now, you can use the function to generate numbers from 0 to the entered number:

trace(rand(3));
// traces 0 or 1 or 2 or 3

If you need to set a specific interval of numbers to generate a random number from (for example, a number from 3 to 10), use this code:

function rand(min:Number, max:Number):Number {
            return(Math.floor(Math.random()*(max-min+1))+ min);
        }

And use it like this:

trace(rand(3, 6));
// traces 3 or 4 or 5 or 6

And that's how you generate random numbers in Actionscript 3!

No comments:

Post a Comment