Generating Random Numbers ActionScript

Generating Random Numbers ActionScript
In our last FlashR CS3 particle system snow scene tutorial, we learned how to generate several instances of the same movie clip by using an ActionScript for loop code. We applied this to our snow scene to generate snow flakes across the top of the stage. However, the flakes are all at the same vertical height because they all have the same Y position.

The scene would be better if we could place the flakes at different and random Y positions. This will cause the flakes to begin falling from different heights in the scene. We can do this by generating a random number for the Y position for each flake using the random() method of the Math class. The Math class is one of the built-in ActionScript classes and contains several methods that perform common math functions such as generating random numbers and rounding numbers. This is only one of the built-in classes that will help to make your life as a Flash programmer much easier.

The first step is to generate a random number between 0 and 1. This only takes one line of code and the number that is generated can be anything from 0 up to but not including 1. You might be thinking that this will not give us very many numbers. But, since the random number can have an infinite number of decimal places, the possibility of different random numbers is infinite. So, here is the magic code.


Here are some examples of the numbers that you might get.


Now, we can take this random number and use it as our Y position. But the difference between the resulting Y positions on the stage is very small making it difficult to see any visible difference. The flakes will still look like they are lined up in a row. It would be better to generate a random number between 0 and 40. To do that, we will multiply the generated random number by 40 which will give us a Y position between 0 and 40 (not including 40).

Math.random() * 40;

Here are some examples of the numbers that you might get this time.



Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map

Content copyright © 2019 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact Diane Cipollo for details.