ActionScript 3.0 Rain – Randomly creating and moving movie clips

View Example | Download Source Files
Creation
There are a couple different ways to create multiple movie clips in AS 3.0 but this is the way I like best. Basically create an array and attach (addChild) the Rain library item to the stage. Place it at a random position within the stage width/height:

var rainArray:Array = new Array();
for (var i:uint=0; i<100; i++) { var raindrop:MovieClip = new Rain(); raindrop.scaleX = Math.random(); raindrop.scaleY = raindrop.scaleX; raindrop.alpha = Math.random(); raindrop.x = Math.round(Math.random() * this.stage.stageWidth); raindrop.y = Math.round(Math.random() * this.stage.stageHeight); addChild(raindrop); rainArray.push(raindrop); }

Motion
Then, to make each move, loop through the length of hte array on ENTER_FRAME and move it’s y position 20 pixels down and its x position 5 pixels to the left (so it goes at a slant). Then, when it reaches the bottom, place the same raindrop back at the top in a random location:
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event):void {
for (var i:uint=0; i rainArray[i].y += 20;
rainArray[i].x -= 5;
if (rainArray[i].y >this.stage.stageHeight){
rainArray[i].y = 0;
rainArray[i].x = Math.round(Math.random() * this.stage.stageWidth);
}
}
}

error

Enjoy this blog? Please spread the word :)