FireworksColdFusionDreamweaverFreehandFlashMXHome
Past Week's New Content

Latest Free Content
View All
Free Content
Accessibility
CMX Learning Guides
Hosted by enterhost

How do you create Random events in Flash?

Knowledge Base

Posted by Matthew David

In this KB you will learn how to use the Random math method.

Life is not organized. It is often random. To allow art imitate life, Flash supports a math command that allows you to pull random events.

Now, before the artists faint or catch hives, controlling math in ActionScript is not hard. With that said, let’s jump into it.

Open up a new movie in Flash and select the first frame. Add the following ActionScript in the Actions Panel:

my_rnd = Math.random() * 5;

trace(my_rnd);

Here you are declaring a new variable called “my_rnd.” The value of “my_rnd” is a random number. The random number is under 5. You can change the number to any value. For instance, you might want the random value of a number between 1 and 100. You would swap the 5 with 100.

You can preview the movie. The Output panel will open and you will get a result that will be between 0 and 5. The value will likely be something like “1.191667097155.” Not a very useful number.

You can force the value to be a whole number by changing the Math.random value to:

my_rnd = Math.floor(Math.random() * 5);

The “Math.floor” command is the closest integer number that is less than or equal to the Math.random value. So, when you preview your results you get a whole number such as “4”.

You can now combine your random number with an If/Else If statement or a Switch statement to add random control to your movie. See, not too hard J