HTML and CSS Reference
In-Depth Information
context object, and the x and y properties we calculated earlier. Finally, it draws the
playerImage on the canvas, and the function is finished:
//Draw Missiles
for (var i=missiles.length−1; i>= 0;i−−) {
context.drawImage(missileImage,missiles[i].x,missiles[i].y);
}
//draw aliens
for (var i=aliens.length−1; i>= 0;i−−) {
context.drawImage(alienImage,aliens[i].x,aliens[i].y);
}
//Draw Player
context.drawImage(playerImage,player.x,player.y);
Like we stated previously, Space Raiders is not a full game. We have only implemented
enough to get the player to shoot missiles so we can play the shoot sound, and to detect
collisions so we can play the explode sound.
Iteration #1: Playing Sounds Using a Single Object
We just described the first iteration of the dynamic audio code. It works by attempting
to call the play() function of both shootSound and explodeSound as often as necessary.
This appears to work at first, but if you listen carefully (and this is apparent on some
browsers more than others), the sounds start to play “off,” or not play at all. This is
because we are using a single object and attempting to play and replay the same sound
over and over. A single HTMLAudioElement was not designed to operate this way. You
can test this example in the code distribution by running CH7EX6.html in your
HTML5-compliant web browser. Press the fire button as quickly as possible and listen
to when and how the sounds play. After a bit, they start to play at the wrong time, don't
finish, or don't play at all. Figure 7-7 shows what the first iteration of Space Raiders
looks like in a web browser.
Iteration #2: Creating Unlimited Dynamic Sound Objects
So, we almost got what we wanted with the first iteration, but we ran into some oddities
when calling the play() function on a single HTMLAudioElement multiple times before
the sound had finished playing.
For our second iteration, we are going to try something different. Let's see what happens
when you simply create a new HTMLAudioElement object every time you want to play a
sound. If this doesn't sound like an efficient use of memory or resources in the web
browser, you are a keen observer. It's actually a horrible idea. However, let's proceed
just to see what happens.
Search WWH ::




Custom Search