Functional Pseudo-Objects

Actionscript:
  1. var moverNum:int = 40;
  2. var movers:Array = new Array();
  3.  
  4. for (var i:int = 0; i<moverNum; i++){
  5.     movers.push(makeMover());
  6. }
  7.  
  8. addEventListener(Event.ENTER_FRAME, onLoop);
  9. function onLoop(evt:Event):void {
  10.     for (var i:int = 0; i<moverNum; i++){
  11.         movers[i]();
  12.     }
  13. }
  14.  
  15. function makeMover():Function{
  16.     // mover vars & setup
  17.     var xVel:Number = Math.random() * 5 + 1;
  18.     var right:Number = stage.stageWidth + 30;
  19.     var s:Shape = Shape(addChild(new Shape()));
  20.     with(s.graphics) beginFill(0xFF0000), drawCircle(0,0,5);
  21.     s.x = Math.random() * stage.stageWidth;
  22.     s.y = Math.random() * stage.stageHeight;
  23.     // return a "run" function
  24.     return function():void {
  25.          s.x += xVel;
  26.          if (s.x> right){
  27.             s.x = -30;
  28.          }
  29.     }
  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...

This entry was posted in functions, motion and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*