HTML and CSS Reference
In-Depth Information
To fill in the 9-pixel imageData object, you need to loop over each of the 9 pixels. Because im- is a one-dimensional array, you can use a single loop to copy the data in. You can optimize
the loop in the draw function by incrementing i by 4 instead of by 1 for each 4 elements of pixel data to prevent
the need for multiplications in the loop.
putImageData is an interesting method because it literally does a blit from the image data onto the Can-
vas—in other words each pixel is copied bit-for-bit ignoring any transparencies. This means it's not generally
a great tool for composition, but in this case because you're just drawing opaque squares, it serves its purpose
quite nicely, with the added advantage of being fast . If you want to use multiple layers of straight pixel data,
you need to use putImageData to place the data onto an off-screen canvas and use drawImage to draw the
image onto the active buffer with globalAlpha set to a number less than 1.
Calling createImageData is actually a (relatively) slow process, so reusing the 3-by-3 square for each
of the particles results in a performance boost.
Is this the only way to do it? Definitely not; there are at least a couple of other methods you could use. One
option is to simply draw a 3-pixel rectangle of the correct color on the page. Another is to use the original image
and draw individual pixel squares of the image instead. This method is just shown as an example of how you
could use putImageData .
To get the particles working, you'll need to modify Ship to create a new explosion object when the it blows
up. Modify the highlighted code below, inside of the ship's step method:
var col;
if(col = this.checkCollision()) {
if(col == 1 && Math.abs(p.vy) < 30) {
if(p.vy > 0) {
p.vy = 0;
} else {
new Q.Explosion(p.x,p.y,p.vx,p.vy,this.imageData)
Adding Particle Wall Collisions
For your purposes this Lander game is almost done, with one missing enhancement to the explosions. Although
the explosions give you the wanted effect, they aren't interacting with the background. Because you already
have access to the pixel data, there's no reason you can't do a quick per-pixel check to get pixel-perfect particle
collisions. Using a simpler version than what you did checking the lander for collisions, as shown in Listing
17-11 , you can update the Explosion.update method to take those walls into consideration. Pretend each
of the particles is only 1-pixel large to simplify the collision detection because moving all these particles at once
can cause a slowdown, especially on mobile browsers.
Listing 17-11: Letting the particles interact with the walls
Search WWH ::

Custom Search