Simple Particles

stage.frameRate = 30;
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void{
	if (int(Math.random()*5)==1){
	  for (var i:int= 0; i<10; i++) createParticle();
	}
}

function createParticle():void{
	var s:MovieClip = new MovieClip();
	s.graphics.beginFill(0);
	s.graphics.drawCircle(0,0,Math.random()*10 + 2);
	s.velX = Math.random()*10-5
	s.velY =  Math.random()*10-5
	s.posX = s.x = 200;
	s.posY = s.y = 200;
	addChild(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.scaleX = s.scaleY -=  .04;
	if (s.scaleX < 0){
		removeChild(s);
		s.removeEventListener(Event.ENTER_FRAME, onRunParticle);
	}
	s.x = s.posX;
	s.y = s.posY;
}

Nothing special here. But my students are always asking me about this – in class I have them alter this code to make fire, water and abstract particle systems.

6 comments

  1. I love your book. Am a beginner and am working my way through. Regarding the above … neat. I’m playing around with it and wondering, if I were going to set these to be in different (random) colors, how would I do that? I’m thinking something along the lines of:

    s.alpha = Math.random()

    but that’s about all I can think of LOL, and would it go right after the drawCircle line (line 12) or or right before addChild (line 17)? Just curious. thanks.

  2. just change line 11:

    s.graphics.beginFill(0);

    to:

    s.graphics.beginFill(Math.random() * 0xFFFFFF);

    and be sure to look at the motion chapter from the book – at the end of the chpater we do exactly this with random colors.

    Glad you are enjoying the book ๐Ÿ™‚

Leave a Reply

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