I l @ ve RuBoard

A good example of the usefulness of random numbers is a snowflake animation. You can create such an animation without ActionScript, but that would mean making as many as 100 snowflake instances, each with its own tweened path .

With ActionScript and random numbers, you can position a snowflake randomly on the screen, give it a random speed and spin, and even move the snowflake back to the top of the screen when it hits the ground so that the snow continues to fall.

1. Create a new movie.

2. Draw a snowflake. Make it a movie clip named Snowflake and name the instance of this movie clip on the screen snowflake.

3. Attach this script to it. This will assign it a random position when the movie starts. It will also have a random vertical speed, horizontal drift , and spin.

` onClipEvent(load) {     this._x = Math.random()*550; // 0 to 550     this._y = Math.random()*400; // 0 to 400     speed = Math.random()*3+3; // 3 to 6     drift = Math.random()*2-1; // -1 to 1     rotate = Math.random()*6-3; // -3 to 3 } onClipEvent(enterFrame) {     this._y += speed;     this._x += drift;     this._rotation += rotate;     // bring back to top     if (this._y > 400) this._y = 0;     // one side to another     if (this._x < 0) this._x = 550;     if (this._x > 550) this._x = 0; } `

When the enterFrame handler runs, it moves the snowflake down by speed and horizontally by drift . It also rotates the snowflake by rotate .

It checks to see whether the snowflake has passed the bottom of the screen and recycles it back to the top if it has.

If the snowflake drifts off the right side of the screen, it is moved to the left side of the screen and vice versa.

4. Test the movie. The snowflake appears somewhere randomly and drifts down. When it hits the bottom, it appears back at the top.

5. Now let's make it really snow. Place this script in the frame on the main timeline:

` // create 50 additional snowflakes for(var i=0;i<50;i++) {     snowflake.duplicateMovieClip("snowflake"+i,i); } `

The duplicateMovieClip function works like the attachMovie function to make a new movie clip while the movie is running. The difference is that it uses an existing movie clip instance and makes an exact copy of it, code and all. You need to give that movie clip a unique name and level.

When you run the movie now, 50 copies of the snowflake are made. Each has its own copy of the same script. Each snowflake, however, generates its own starting location, speed, drift, and rotation. So you end up with a field of random snowflakes.

You can check the movie 11snowflakes.fla to see this movie in action. It looks something like Figure 11.3.

##### Figure 11.3. A field of 51 random snowflakes.

 I l @ ve RuBoard

Sams Teach Yourself Flash MX ActionScript in 24 Hours
ISBN: 0672323850
EAN: 2147483647
Year: 2002
Pages: 272