HTML and CSS Reference
In-Depth Information
}
},
After the
init
method has run, the
Explosion
will have a set of pixels that match the original color of
the pixels from the ship that can spread out and move independently.
Drawing Pixels
With the particles created, you need to take care of the two remaining sprite functions to finish off the
Q.Explosion
class:
update
and
draw
(see
Listing 17-10
.
) For
update
, the function needs to add in the
effects of gravity on the exploding particles and then step each particle using forward Euler. The
draw
function
does something a little more interesting. In the preceding initialization function, you created a 3-pixel by 3-pixel
imageData
object for use by the
draw
function. You need to fill up that 9-pixel
imageData
object with
the color of each particle and then draw it to the Canvas by using the
Canvas putImageData
method (see
Listing 17-10:
Updating and drawing the explosion particles
step: function(dt) {
for(var i =0,len=this.particles.length;i<len;i++) {
var v = this.particles[i];
if(v.lifetime > 0) {
v.vy += 20 * dt;
v.x += dt * v.vx;
v.y += dt * v.vy;
v.lifetime -= dt
}
if(v.lifetime <= 0) { Q.stageScene('level'); return; }
}
},
draw: function(ctx) {
for(var i=0,len=this.particles.length;i<len;i++) {
var v = this.particles[i];
if(v.lifetime > 0) {
for(var l=0;l<36;l+=4) {
this.drawPixel[l+0] = v.r;
this.drawPixel[l+1] = v.g;
this.drawPixel[l+2] = v.b;
this.drawPixel[l+3] = v.a;
}
ctx.putImageData(this.pixelData,v.x,v.y);
}
}