HTML and CSS Reference
In-Depth Information
objects, unspecific to the type of on-screen object that they represent. This means that
we can add any other type of object to this game (boss alien, power-ups, enemy missiles,
etc.), and if it is created with similar properties, we can use the same function to test
collisions against it.
The function works by finding the top, left, bottom, and right values for each object,
and then testing to see whether any of those values overlap. Bounding box collision
detection will be discussed in detail in Chapter 8 , but we just wanted to give you a
preview of what it looks like for Space Raiders :
function hitTest(image1,image2) {
r1left = image1.x;
r1top = image1.y;
r1right = image1.x + image1.width;
r1bottom = image1.y + image1.height;
r2left = image2.x;
r2top = image2.y;
r2right = image2.x + image2.width;
r2bottom = image2.y + image2.height;
retval = false;
if ( (r1left > r2right) || (r1right < r2left) || (r1bottom < r2top) ||
(r1top > r2bottom) ) {
retval = false;
} else {
retval = true;
return retval;
Playing the game
Now the game is ready to play. STATE_PLAYING calls the drawScreen() function, which
is the heart of Space Raiders . The first part of this function simply moves the missiles
and aliens on the screen. Moving the missiles is quite easy. We loop through the array
(backward), updating the y property of each with the speed property. If they move off
the top of the screen, we remove them from the array. We move through the array
backward so that we can splice() array elements out of the array and not affect loop
length. If we did not do this, elements would be skipped after we splice() the array:
for (var i=missiles.length-1; i>= 0;i−−) {
missiles[i].y −= missiles[i].speed;
if (missiles[i].y < (0-missiles[i].height)) {
Drawing the aliens is similar to drawing missiles—with a few exceptions. Aliens move
left and right, and when they reach the side of the canvas, they move down 20 pixels
Search WWH ::

Custom Search