Game Development Reference
In-Depth Information
Implementing the emitter
For our fireworks emitter, we want to pick a random point on the canvas. We then spawn 100 particles at
that point and give them random velocities. This will make them fly off into different directions.
function emit(system, width, height){
var position = new Vec2(Math.random()*width, Math.random()*height);
for(var i = 0; i < 100; i++) {
var particle = new Particle(position.copy());
particle.velocity.x = fuzzy(100);
particle.velocity.y = fuzzy(100);
particle.image = spark;
system.particles.push(particle);
}
}
You can view the result of this in fireworks.0.html . As you can see, the pattern generated by the sparks
looks a bit square. This is because we initialized the velocities independently. We can simply adjust this to
create circles or spheres.
var particle = new Particle(position.copy()),
alpha = fuzzy(Math.PI),
radius = Math.random()*100;
particle.velocity.x = Math.cos(alpha)*radius;
particle.velocity.y = Math.sin(alpha)*radius;
particle.image = spark;
When the radius is randomized, you will get a sphere-like shape; when it is constant (radius = 50, for
example), you will get a circle. Note that to get an even distribution, you would need to use the square root
of the radius but, in my opinion, it looks better without it. You can see this in fireworks.1.html . Try to find
other creative shapes on your own!
Forces
Right now, our fireworks look like they are in a vacuum and not affected by gravity or air. We can easily
change this by adding some forces to the simulation.
A simple way to define gravity would be like this:
function gravity(particle, td){
particle.velocity.y += td*10;
}
This is very specific, however. Often it makes sense to define forces in a more general way. Gravity, for
example, is nothing but constant acceleration.
function accelerationf(force){
return function(particle, td){
particle.velocity.iadd(force.muls(td));
};
}
var gravity = accelerationf(new Vec2(0, 50));
 
Search WWH ::




Custom Search