While the random function is quite limited when used alone, you can
configure it to generate numbers that fall within a defined range. More than
likely, for all of your animations, you would want to set a range criteria for
the random numbers.
To configure a number to randomly fall within a range, you would use the
following format:
Math.floor(Math.random() * (high - low)) + low;
The text high refers the
highest possible value the random number function will generate. Likewise,
low produces the least
possible value for a random number. You should note that you are not limited
to using only positive values. You can set low to be a negative number, and
the range of the random numbers will still fall within
high and
low.
For example, let's look at the following line of code:
Math.floor(Math.random() * (70 - 7)) + 7;
A random number between 7 and 63 will be displayed. If you look at the line
of code, you will see the function Math.floor()
added prior to the Math.random()
function.
When a random number is defined, it is usually not a nice, round number.
The answer will have numerous digits following a decimal point such as
5.1403533. In order to round the number into a nice, solid integer,
Math.floor() is used.
Math.floor() takes a number and rounds it
down to the closest integer less than or equal to the number in question. For
example, Math.floor(5.1403533) will yield 5.
You can also use Math.round(), but that will
be saved for another time.
Many of the tutorials in this site will use the
Math.random() function, so I hope this little tip helps you understand
this little facet of Flash programming lingo.
Thanks to Scootman on the forums for noticing a blatant error I made while
writing the first version of this tutorial!
Happy Flashing!
Kirupa Chinnathambi