10,000 Transparent Sprites?

October 8th, 2008

If you interested in the idea behind the fast drawing library that I'm working on... the best way I can explain it is with a little code. The following code snippet creates 10,000 transparent circles that follow the mouse. Run this code in your flash timeline:

Actionscript:
  1. stage.frameRate = 31;
  2.  
  3. var imageNum:int = 10000;
  4.  
  5. var point:Point = new Point(0,0);
  6.  
  7. var s:Sprite = new Sprite();
  8. s.graphics.beginFill(0xCCCCCC);
  9. s.graphics.lineStyle(0,0x000000);
  10. s.graphics.drawCircle(3,3,3);
  11. s.alpha = .2;
  12.  
  13. var nested:Sprite = new Sprite();
  14. nested.addChild(s);
  15.  
  16. var image:BitmapData = new BitmapData(s.width, s.height, true, 0x00000000);
  17. image.draw(nested);
  18.  
  19. var canvas:BitmapData = new BitmapData(400,400, true, 0xFFFFFFFF);
  20.  
  21. var frame:Bitmap = new Bitmap(canvas);
  22.  
  23. addChild(frame);
  24.  
  25. var xPos:Array = new Array();
  26. var yPos:Array = new Array();
  27.  
  28. for (var i:int = 0; i<imageNum; i++){
  29.     xPos.push(Math.random()*400);
  30.     yPos.push(Math.random()*400);
  31. }
  32.  
  33. addEventListener(Event.ENTER_FRAME, onLoop);
  34.  
  35. function onLoop(evt:Event):void {
  36.    
  37.     canvas.fillRect(new Rectangle(0,0,400,400), 0xFFFFFFFF);
  38.  
  39.     var div:Number;
  40.     for (var i:int = 0; i<imageNum; i++){
  41.         div  = (i / 100)+2;
  42.         xPos[i] += (mouseX - xPos[i])/div;
  43.         yPos[i] += (mouseY - yPos[i])/div;
  44.         point.x = xPos[i];
  45.         point.y = yPos[i];
  46.         canvas.copyPixels(image, image.rect, point, null, null, true)
  47.     }   
  48. }

The library is made up of a handful of these kinds of techniques. Adding classes into the mix actually seems to slow things down a few milliseconds, buts its worth it so you don't have to reinvent the wheel every time you want to draw lots of things to the stage.

Leave a Reply