creating a simple particle system

This week I decided to go over creating a basic particle system. Particle systems are fun to play with, and as you will soon find out, easy to start experimenting with.

The Particle Object

First we will create a particle object. For our particle object, we will extend the Bitmap Class. We could alternatively extend sprite, movieclip or shape for our particle object. Bitmap is good in this case because we don’t need any of the functionality that the other objects offer, and helps us to keep the resource needs down. Lets look at the Particle object.

public function Particle(bitmapData:BitmapData, speed):void {
    super(bitmapData);
    this.speed = speed;
}

As you can see from this constructor function, the particle object is an extremely simple object. All we are adding to the standard Bitmap object is the speed variable. By adding this to our particle object, each instance of it can have a unique speed value. This is helpful in creating a more organic feel in our system.

Setting it up

The next step is to create multiple instances of particle object, storing each one in an array for access later on. In the code below, I assign the variable speed a random number. I then use that same value to affect the scale of the particle objects. The result of this is that bigger particles will move faster, (due to there higher speed value), which creates the illusion of depth in the system. I am also spreading out the particles randomly across the x and y axis of the stage. If we don’t do this they will all be created on top of one another.

var p:Particle = new Particle(myBitmapData, Math.random() * 5 + 2);
p.x = Math.random() * myStageWidth;
p.y = Math.random() * myStageHeight;
p.scaleX = p.scaleY = p.speed/10
_particles.push(p);
addChild(p);

Animating it

Now that all the particles are created all that is left to do is update their individual positions on a enterframe loop as seen in the code below.

var l:int = _particles.length;
for(var i:int = 0; i) {
    var p:Particle = _particles[i] as Particle;
    if(p.y > myStageHeight) p.y = -30;
    if(p.x > myStageWidth) p.x = -10;

    p.y += p.speed;
    p.x += p.speed;
}

A quick if statement checks to see if the particle has left the stage area, if so, it is repositioned on the stage where it can fall back into view. Afterwards each particle’s position is update based on its speed value, resulting in the example below.

Grab the example files here.

Comments

Comment functionality has been disabled. Contact me on Twitter.

gaming community said:

Great post, adding it to my bookmarks!

Hosting said:

Great article, adding it to my favourites!

Tyler Egeto said:

Note: this doesn’t work anymore!

Recent & Popular Articles

Browse All >