10,000 Transparent Sprites?
Wednesday, October 8th, 2008If 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:
-
stage.frameRate = 31;
-
-
var imageNum:int = 10000;
-
-
var point:Point = new Point(0,0);
-
-
var s:Sprite = new Sprite();
-
s.graphics.beginFill(0xCCCCCC);
-
s.graphics.lineStyle(0,0x000000);
-
s.graphics.drawCircle(3,3,3);
-
s.alpha = .2;
-
-
var nested:Sprite = new Sprite();
-
nested.addChild(s);
-
-
var image:BitmapData = new BitmapData(s.width, s.height, true, 0x00000000);
-
image.draw(nested);
-
-
var canvas:BitmapData = new BitmapData(400,400, true, 0xFFFFFFFF);
-
-
var frame:Bitmap = new Bitmap(canvas);
-
-
addChild(frame);
-
-
var xPos:Array = new Array();
-
var yPos:Array = new Array();
-
-
for (var i:int = 0; i<imageNum; i++){
-
xPos.push(Math.random()*400);
-
yPos.push(Math.random()*400);
-
}
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
-
function onLoop(evt:Event):void {
-
-
canvas.fillRect(new Rectangle(0,0,400,400), 0xFFFFFFFF);
-
-
var div:Number;
-
for (var i:int = 0; i<imageNum; i++){
-
div = (i / 100)+2;
-
xPos[i] += (mouseX - xPos[i])/div;
-
yPos[i] += (mouseY - yPos[i])/div;
-
point.x = xPos[i];
-
point.y = yPos[i];
-
canvas.copyPixels(image, image.rect, point, null, null, true)
-
}
-
}
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.