Game Development Reference
In-Depth Information
In addition to gravity, we also want to simulate the air the fireworks are in. There are two interesting forces
to do this: drag (air resistance) and wind.
function dampingf(damping){
return function(particle, td){
particle.velocity.imuls(damping);
};
}
var drag = dampingf(0.97);
function wind(particle, td){
particle.velocity.x += td*Math.random()*50;
}
Again, drag is derived from a simpler damping function. With all the forces defined, we can now add them
to our simulation.
system = new ParticleSystem();
system.forces.push(gravity);
system.forces.push(wind);
system.forces.push(drag);
emit(system, canvas.width, canvas.height);
As you can see in fireworks.2.html , our effect already looks more realistic.
Life and death
Nothing lasts forever, except for our fireworks. That's bad. For one, it looks very wrong, but it is also
resulting in a memory leak because particles are never, ever removed from the system. To fix this, we
need to add an age to our particles and remove them when they have exceeded that age.
We can implement this with two simple changes to our particle engine. We add an age property to our
particle instances and we define a maxAge of Infinity on the prototype. In the update function, we update
the age and return whether the particle is still alive. The updated particle will look like this:
function Particle(position) {
this.position = position;
this.velocity = new Vec2(0, 0);
this.age = 0;
}
Particle.prototype = {
maxAge: Infinity,
update: function(td) {
this.age += td;
this.position.iadd(this.velocity.muls(td));
return this.age < this.maxAge;
}
}
 
Search WWH ::




Custom Search