Generating Random Numbers ActionScript - 2

Generating Random Numbers ActionScript - 2
OK, we are ready to add this to the ActionScript for our snow scene. Here is what our code looks like at this point. Now, we will add code to position each flake at a random Y position between 0 and 40. We just need to add one line of code that sets the Y position for our _Snowflake to a random number between 0 and 40.

_Snowflake.y = Math.random() * 40;

Go to Frame 1 on the Actions Layer in the Timeline. Open the Actions Panel and add this line of code just before the closing curly bracket.

Test your movie several times and you will see that the flakes are in different positions each time.

OK, now that we know that it does work, let's do the same for the placement of the flakes along the horizontal line. We just need to change the line of code that places each instance of the movie clip 50 pixels apart.

_Snowflake.x = i * 50;

We can use the same Math.random() function to place the flakes at random positions along the horizontal axis. Let's replace the code "i * 50" with "Math.random() * 40;". Test your movie again. What happened? We have all the flakes bunched together at the left of the stage. Why? Our stage is 550 pixels wide and we are using random numbers between 0 and 39. We need to change the "50" to "550" and test again.

OK, that's better but some of the flakes are being cut off on the right edge of the stage. We need to narrow our scope just a little to take into account that the flakes are 35 pixels wide. Let's change the 550 to 510 and test again. Now the flakes are falling within the stage and not being cut off at the edge. That's good enough for now. Here is the code that we have written.

var _Snowflake:mcSnowflake;

for (var i:Number = 0; i < 10; i++)
_Snowflake = new mcSnowflake();
_Snowflake.x = Math.random() * 510;
_Snowflake.y = Math.random() * 40;

For reference, save your snow scene as SnowScene3.fla.

Copyright 2018 Adobe Systems Incorporated. All rights reserved. Adobe product screen shot(s) reprinted with permission from Adobe Systems Incorporated. Adobe, Photoshop, Photoshop Album, Photoshop Elements, Illustrator, InDesign, GoLive, Acrobat, Cue, Premiere Pro, Premiere Elements, Bridge, After Effects, InCopy, Dreamweaver, Flash, ActionScript, Fireworks, Contribute, Captivate, Flash Catalyst and Flash Paper is/are either [a] registered trademark[s] or a trademark[s] of Adobe Systems Incorporated in the United States and/or other countries.


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.