HTML and CSS Reference
In-Depth Information
function
function eventMouseUp ( event ) {
missiles . push ({ speed : 5 , x : player . x + . 5 * playerImage . width ,
y : player . y - missileImage . height , width : missileImage . width ,
height : missileImage . height });
Nextisthefirstreally critical lineofcodeforthesubject athand:audio.Forthisfirstiteration
of SpaceRaiders ,wesimplycallthe play() functionof shootSound .Thiswillplaytheshoot
sound as often as the player presses the left mouse button (in theory):
shootSound . play ();
}
Bounding box collision detection
Before we get to the main part of the game logic, we should discuss bounding box collision
detection. We need to detect collisions between the missiles the player fires and the aliens the
playerisfiringupon.Todothis,wewillcreate afunctionthatteststoseewhethertwoobjects
are overlapping. For lack of a better name, we call this function hitTest() .
Thetypeofhittestwearegoingtoperformiscalledaboundingboxcollisiontest.Thismeans
that we are going to ignore the intricate details of the bitmapped graphics and simply test to
see whether an invisible “box” drawn around the bounds of each object overlaps with a simil-
ar box drawn around the other objects.
Recallthatboththe alien and missile dynamicobjectswerecreatedwithsimilarproperties:
x , y , width , height . This was so that the hitTest() function could test them as generic ob-
jects,unspecifictothetypeofon-screenobjectthattheyrepresent.Thismeansthatwecanadd
any other type of object to this game (boss alien, power-ups, enemy missiles, and so on), 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
discussedindetailin Chapter 8 ,butwejustwantedtogiveyouapreviewofwhatitlookslike
for Space Raiders :
function
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 ;
Search WWH ::




Custom Search