Snowflall
Now the movie is populated with snow, all thats left is to make it fall.
amount = 100;
mWidth = Stage.width;
mHeight = Stage.height;
for (var i = 0; i<amount; i++) {
thisFlake = this.attachMovie("flake", "flake"+i, i);
with (thisFlake) {
_x = Math.random()*mWidth;
_y = Math.random()*mHeight;
_xscale = _yscale=_alpha=40+Math.random()*60;
}
}
thisFlake.yspeed = Math.random()*2+ .1;
thisFlake.onEnterFrame = function() {
this._y += this.yspeed;
if (this._y>=mHeight) {
this._y = -10;
this._x = -10+Math.random()*mWidth;
}
}
The main thing that has been added is the yspeed variable, the speed is determined randomly for each flake, then the _y position of the flake is incremented on enter frame.
The if statement resets the flake to the top of the screen each time the _y value exceeds the total height of the movie and moves out of the screen.
Triganometry and Realism
At this point you have a very basic snow effect this can be enhanced very easily by adding a bit more actionscript.
amount = 100;
mWidth = Stage.width;
mHeight = Stage.height;
for (var i = 0; i<amount; i++) {
thisFlake = this.attachMovie("flake", "flake"+i, i);
with (thisFlake) {
_x = Math.random()*mWidth;
_y = Math.random()*mHeight;
_xscale = _yscale=_alpha=40+Math.random()*60;
}
thisFlake.yspeed = Math.random()*2+ .1;
thisFlake.increment = -0.025+Math.random()*0.05;
thisFlake.onEnterFrame = function() {
this.radians += this.increment;
this._y += this.yspeed;
this._x += Math.sin(this.radians);
if (this._y>=mHeight) {
this._y = -10;
this._x = -10+Math.random()*mWidth;
}
if (this._x>=mWidth || this._x<=0) {
this._y = -10;
this._x = -10+Math.random()*mWidth;
}
}
}
The chages here are in order to create a bit of a drifting motion rather than having the snowfall directly.
The _x property is set to using the sin function. The angle used in the sine function is incremented to give the snow flake a sinusoidal (wavey) motion. The amount the angle is incremented by is randomly set for each flake so that all the flakes move independently. Note that flash uses radians for measuring angles.
Another if statement has also been added which will reset the flake if it moves beyond the width of the movie.
Return to page 1 of the flash snow tutorial