HTML and CSS Reference
In-Depth Information
r2bottom = image2 . y + image2 . height ;
retval = false
false ;
iif ( ( r1left > r2right ) || ( r1right < r2left ) || ( r1bottom < r2top ) ||
( r1top > r2bottom ) ) {
retval = false
false ;
} else
else {
retval = true
true ;
}
return
return retval ;
}
Playing the game
Nowthegameisreadytoplay. STATE_PLAYING callsthe drawScreen() function,whichisthe
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 re-
move them from the array. We move through the array backward so that we can splice() ar-
ray 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
for ( var
var i = missiles . length - 1 ; i >= 0 ; i −− ) {
missiles [ i ]. y = missiles [ i ]. speed ;
iif ( missiles [ i ]. y < ( 0 - missiles [ i ]. height )) {
missiles . splice ( i , 1 );
}
}
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 and then
reverse direction. To achieve the reversal in direction, multiply the speed property by −1 . If
the aliens are moving to the right ( speed = 2 ),this will make the speed property equal to −2 ,
which will subtract from the x position and move the aliens to the left. If the aliens hit the left
side of the canvas, the speed property will again be multiplied by −1 ( −2 * −1 ), which will
equal 2 . The alien will then move to the right because 2 will be added to the x value for the
alien each time drawScreen() is called:
//Move Aliens
for
for ( var
var i = aliens . length 1 ; i >= 0 ; i −− ) {
aliens [ i ]. x += aliens [ i ]. speed ;
Search WWH ::

Custom Search