BitmapData & Particles

stage.frameRate = 30;
stage.quality = StageQuality.LOW;

var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
addChild(new Bitmap(canvas));
var overlay:BitmapData = new BitmapData(400,400,true, 0x12000000);
var particles:Dictionary = new Dictionary(true);

var blur:Array = [new BlurFilter(8,8,1)];
	
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	for (var i:int= 0; i<3; i++) createParticle();
	canvas.copyPixels(overlay, canvas.rect, new Point(0,0), null, null, true);
}
 
function createParticle():void{
	var s:MovieClip = new MovieClip();
	var diameter:Number = Math.random()*50 + 2;
	var radius:Number = diameter / 2;
	var mat:Matrix = new Matrix();
    mat.createGradientBox(diameter, diameter, 0, -radius, -radius);
	mat.createGradientBox(diameter, diameter, 0, -radius, -radius);
    s.graphics.beginGradientFill(GradientType.RADIAL, [ 0xFFCC32, 0xFF0000], [0.5,0.8], [0, 255], mat, SpreadMethod.PAD);
	s.graphics.drawCircle(0,0,radius);
	s.velX = 0;
	s.velY =  -Math.random()*6 + 3;
	s.posX = s.x = 150+ Math.random() * 100;
	s.posY = s.y = 200;
	s.theta= Math.random() * Math.PI * 2;
	s.inc = Math.random() * 0.4 + 0.01;
	s.rad = Math.random() * 4 + 1;
	s.filters = blur;
	// since the particles aren't on the display list, we need to keep a reference to them
	particles[s] = s;
	s.addEventListener(Event.ENTER_FRAME, onRunParticle);
}
function onRunParticle(evt:Event):void {
	var s:MovieClip = MovieClip(evt.currentTarget);
	s.posX += s.velX;
	s.posY += s.velY;
	s.velX = s.rad * Math.cos(s.theta);
	s.theta += s.inc;
	s.scaleX = s.scaleY -=  .03;
	if (s.scaleX < 0){
		particles[s] = null;
		s.removeEventListener(Event.ENTER_FRAME, onRunParticle);
	}
	s.x = s.posX;
	s.y = s.posY;
	canvas.draw(s, s.transform.matrix, null, BlendMode.ADD);
}

This is a slight variation on a simple particle system that I show in my intermediate class. It is almost the same as this example. But it makes use of filters and BitmapData.

Here is a still generated with this snippet. You’ll notice it vaguely resembles fire.

If you need more particles, there are other approaches that are more appropriate.

Leave a Reply

Your email address will not be published. Required fields are marked *