1. Home
  2. Computing & Technology
  3. Animation

Flash Falling Snow with Random Functions and Movie Clips

By , About.com Guide

8 of 10

Now let’s look at the onClipEvent (enterFrame) that controls the random downward drift:

onClipEvent (enterFrame) {
pos = pos + (Math.random()*.1) ;
this._x = this._x + Math.sin(pos) ;
this._y = this._y + 1 + Math.random()*3;
if (this._y>=400) {
this._y = this._y – 500 + Math.random()*100;
this._x = 0 + Math.random()*575;
}
}

To break this down:

pos is a variable created to help control the back-and-forth drift of the snowflake; we define the x position each time that the movie enters the frame as the previous frame’s x position plus the sine of variable pos. Because a sine value can return either a positive or negative value, sometimes adding the value returned by Math.sin actually ends up subtracting from the current x position instead of adding to it, causing backwards motion. pos also changes, by generating a random number, multiplying it by .1 (this is just a random number I chose, but you can use any number you want depending how you want the snowflake to oscillate), then adding it to the value of pos from the previous iteration.

The y (vertical) position is much simpler; it’s defined as the previous y position advanced by one pixel, plus a little extra advancement that could be anywhere from .3 to 3 pixels, so that every snowflake falls at a different speed. Although my Math.random() generated number is multiplied by 3, you can again enter any integer or even a Math constant to customize your snowfall to a speed that suits you.

Lastly, an if statement checks to see if the snowflake has reached the bottom (a pixel coordinate equal to the height of the movie) and, if it has, sends it zipping back up to the top while generating a new random x position.

Explore Animation
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Animation
  4. Flash Animation Tutorials
  5. Flash Falling Snow with Random Functions and Movie Clips

©2009 About.com, a part of The New York Times Company.

All rights reserved.