Random Numbers

Random Numbers

Flash CS4 ActionScript 3.0 Tutorial

 

How to Generate Random Numbers with Flash ActionScript

 

 

The random number generator outputs numbers between zero and one (excluding the number one). Each time the method is called, another number is generated.

Tutorial Elements

Movie Symbol with instance name bar01_mc

Movie Symbol with instance name bar02_mc

Movie Symbol with instance name bar03_mc

 

Step One

Open a new Flash document and add a new layer.

Step Two

Name the upper layer Actions and the lower layer Content.

Step Three

Click the keyframe for the Content layer.

Step Four

Add three Movie Symbols with the instance names of bar01_mc, bar02_mc and bar03_mc. Set the registration point at the bottom for each symbol. For more information on creating Movie Symbols and Naming Instances, see topics, Movie Symbol Basics and Instance Naming.

Step Five

Option double-click (PC - Alt double-click) the keyframe of the Actions layer to open the ActionScript panel.

Step Six

Copy/Paste the following code to the ActionScript panel.

addEventListener(Event.ENTER_FRAME, barScale);

function barScale(e:Event):void{

bar01_mc.scaleY=2*Math.random();

bar02_mc.scaleY=2*Math.random();

bar03_mc.scaleY=2*Math.random();

}

Step Seven

Click the Auto Format button to format the code

Step Eight

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). The bars are scaled randomly in the y direction at the files frame rate.

Dissecting the Code

The first line adds an Event Listener that activates the barScale function at the file's frame rate. If the file is set to 18 frames per second, then the function fires 18 times per second.

The code inside the curly braces of the function determines what the function will do. A random number is generated for each bar instance. The random value is doubled, causing the bars to bounce upward.

 

Contribute Ad