Wednesday, February 6, 2013

Picking Apart Particle Systems

Particle Systems are interesting. They can be complicated, or very simple, all depending on how much effort you wish to put into it They can look anything like this from Giladlotan, to this from Mr. Speaker . They can be created quite simply with HTML5 and JavaScript using objects. First,create a basic canvas, prepare it for drawing, and have a draw loop set up . If you don't know how to do this, simply Google it, there's plenty of great tutorials. Secondly, you create the object.

function particle(x,y) {
this.x=x;
this.y=y
}


Now we have our basic particle. This will be used several times throughout the code. We then need to create an array to store the information. At the top of your code, insert this: var particles = []; This initializes an empty array of particles. When run, it does nothing special. so let's add some particles to the array.


particles.push(new particle(0,0));
particles.push(new particle(50,50));
particles.push(new particle(100,100));
particles.push(new particle(100,100));
This will still do nothing, this is because we never draw the particles. Let's change the particle code a bit to function properly.


function particle(x,y) {
   this.x=x;
   this.y=y;
   this.draw=function() {

      context.fillRect(this.x,this.y,5,5)

   }
}
This is then called by the draw method using the following code:
for(var i=0;i<particles.length;i++) {
    particles[i].draw();
}
Then, you have some dots on the screen. So let's move them. Create an update function in the particle class and call it every update.
this.update=function() {
   this.x+=9.8
               //constant rate of gravity
}
Voila. We have ourselves a very simple particle control system. Add some more, using a while loop, a for loop, or a mousemove event, add a background, and some particle images, and you get something like this:

No comments:

Post a Comment