HTML and CSS Reference
In-Depth Information
iif ( aliens [ i ]. x > ( theCanvas . width - aliens [ i ]. width ) ||
aliens [ i ]. x < 0 ) {
aliens [ i ]. speed *= 1 ;
aliens [ i ]. y += 20 ;
}
iif ( aliens [ i ]. y > theCanvas . height ) {
aliens . splice ( i , 1 );
}
}
Thenextstepin drawScreen() istodetectcollisionsbetweenthealiensandthemissiles.This
part of the code loops through the missiles array backward while nesting a loop through the
aliens array.Itwilltesteverymissileagainsteveryalientodeterminewhetherthereisacolli-
sion.Becausewehavealreadycoveredthe hitTest() function,weneedtodiscussonlywhat
happens if a collision is detected. First, we call the play() function of the explodeSound .
This is the second critical line of code in this iteration of Space Raiders , because it plays (or
attempts to play) the explosion sound every time a collision is detected. After that, it splices
the alien and missile objects out of their respective arrays and then breaks out of the nes-
ted for:next loop. If there are no aliens left to shoot, we set the appState to STATE_RESET ,
which will add more aliens to the canvas so that the player can continue shooting:
missile : for
for ( var
var i = missiles . length 1 ; i >= 0 ; i −− ) {
var
var tempMissile = missiles [ i ]
for
for ( var
var j = aliens . length - 1 ; j >= 0 ; j −− ) {
var
var tempAlien = aliens [ j ];
iif ( hitTest ( tempMissile , tempAlien )) {
explodeSound . play ();
missiles . splice ( i , 1 );
aliens . splice ( j , 1 );
break
break missile ;
}
}
iif ( aliens . length <= 0 ) {
appState = STATE_RESET ;
}
}
The last few lines of code in drawScreen() loop through the missiles and aliens arrays
and draw them onto the canvas. This is done using the drawImage() method of the context
object and using the x and y properties we calculated earlier. Finally, it draws the player-
Image on the canvas, and the function is finished:
Search WWH ::




Custom Search