Creating a Particle System Wind Effect with Flash CS3 and Math.random()

Now that we have our snowflake falling in our FlashR particle system, let's modify the ActionScript 3 code a little. Our flake just falls straight down. But, unless there is absolutely no wind, most flakes travel down at a slant. So let's use some math to make our flake move to the right slightly as it falls. To add more realism, we want the amount of horizontal movement to change as the snowflake makes it's way down the stage.

Remember, that in one of our earlier tutorials in this series, we placed flakes at different positions horizontally along the top of the stage. We did this by setting different values for the X position for each flake. So in this tutorial, we can use the same _Snowflake.x property again to control the horizontal movement in the animation.

Secondly, when we created our flake, we set the flake's initial X and Y positions to a random number.

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

We can use the same Math.random() to control the amount of random horizontal movement. Have you guess what comes next?

We know that on each frame of our Flash movie, we call the snowfall function.

stage.addEventListener(Event.ENTER_FRAME, snowfall);

This function increases the_Snowflake.y property by 10 for every frame. This is what moves the flake down the stage.

_Snowflake.y += 10;

But that is too fast for us to see the subtle horizontal movement that we will add next. So, let's slow it down a little by changing the 10 to a 5.

_Snowflake.y += 5;

Now we can use the same code to move the flake horizontally to the right. All we need to do is change the_Snowflake.y to_Snowflake.x.

_Snowflake.x += 10;

Now the snowflake will move 10 pixels to the right and 5 pixels down at each frame in our Flash movie. But, it would be more realistic if the snowflake's horizontal movement was more random as it makes it's way down the stage. We can do this by substituting the 10 with a random number between 0 and 9. We will use the Math.random() to do this.

But now that we are moving the flake to the right, it might eventually go beyond the right side of the screen. Remember that we stopped the snowflake if it fell below the stage.

if ( _Snowflake.y> 370 )

We can also stop it if it goes beyond the right side of the stage. Let's add that to our conditional statement. Because we want the animation to stop if either the first OR the second of these conditions are true, we can use the || operator between the two conditions in the if statement.

if ( _Snowflake.y> 370 || _Snowflake.x> 550)

If either one of these conditions are true, Flash will remove the ENTER_FRAME event listener.