-
var moverNum:int = 40;
-
var movers:Array = new Array();
-
-
for (var i:int = 0; i<moverNum; i++){
-
movers.push(makeMover());
-
}
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
for (var i:int = 0; i<moverNum; i++){
-
movers[i]();
-
}
-
}
-
-
function makeMover():Function{
-
// mover vars & setup
-
var xVel:Number = Math.random() * 5 + 1;
-
var right:Number = stage.stageWidth + 30;
-
var s:Shape = Shape(addChild(new Shape()));
-
with(s.graphics) beginFill(0xFF0000), drawCircle(0,0,5);
-
s.x = Math.random() * stage.stageWidth;
-
s.y = Math.random() * stage.stageHeight;
-
// return a "run" function
-
return function():void {
-
s.x += xVel;
-
if (s.x> right){
-
s.x = -30;
-
}
-
}
-
}
This snippet creates 40 shapes that move to the right at a random velocity. When they animate off the right hand side of the stage they return from the left.
The makeMover() function has a series of variable definitions related to the x velocity and position of a Shape. The makeMover() function then returns an anonymous function that contains some logic to move the Shape "s". The anonymous function has access to the makeMover() functions temporary variables...
On the main loop we run all of the anonymous functions - animating all the shapes by their random x velocities.
It would be interesting to write the same program using classes and test the for speed differences. My assumption is that anonymous functions are expensive, but it would still be interesting to see...