HTML and CSS Reference
In-Depth Information
Congratulations! You now have pixel-perfect collisions between your background and your ship, so creating
a new level is as easy as creating a new level image. If you want to see the results, you can run
lander_collision.html from the chapter code. When you crash, you need to press the Reload button on
your browser to restart the game.
Although the code in Listing 17-7 works, it's ripe for some optimization. If this were a production game,
you'd take a deep look at the best way to optimize the inner loop of the checkCollision code. One quick
optimization would be to modify the loop variables to increment by a number other than 1 to prevent the need
for multiplications in the pixel data lookups. (Multiplications take more time for CPUs to perform than addi-
tions.) This optimization is left as an exercise to try on your own.
Restrictions with getImageData
Using Canvas with getImageData has a few restrictions associated with it that you should be aware of. If you
pull an image into your Canvas from a different domain, that Canvas becomes “tainted,” so you can't use
getImageData on that Canvas. This was a restriction that was put in place to prevent access to images that
might contain personal information from other websites because images are loaded with full cookies sent to that
Making It Go Boom
Right now in the current version of Lander, you don't get a dramatic ship death—the ship just stops. You can
fix that with the help of some exploding pixels. You create a new class that takes the pixels of the lander and
explodes them when you die. This amounts to a simplified pixel-based particle engine.
Adding an Explosion Class
To start, you need to create a new class called Explosion . Although it's going to act like the sprites you are
familiar with, in that it'll have an update and a draw method, you can inherit it straight from the base class
because you don't need any existing functionality.
The init method is going to take in some information about the about-to-be-particlized
lander—specifically its location, velocity, and image data—and create a series of particles, each with their own
location and velocity representing one pixel from the input lander image. For performance reasons you won't
turn every pixel of the lander into a particle; rather you just sample every fourth pixel and create particles of
3 pixels by 3 pixels in size. This is an arbitrary decision—play with the init code to generate different-sized
particles to get a sense of performance. Listing 17-9 shows the commented init code.
Listing 17-9: Explosion init method
Q.Explosion = Q.GameObject.extend({
init: function(x,y,vx,vy,imgData) {
// Set up a container for our pixels
this.particles = []
Search WWH ::

Custom Search