Game Development Reference
In-Depth Information
In addition to the constructor, you add a method called play . In this method, you load the sound,
and you set an attribute called autoplay to true. The result of this is that the sound will immediately
start playing after it's loaded. If the sound doesn't need to loop, you're done and can return from the
method. If you do require the sound to loop, you need to reload and play the sound again after it has
finished playing. The Audio type allows you to attach functions to so-called events . When an event
occurs, the function you attached is executed. Examples are the event that the audio has started
playing, or the event that the audio has finished playing.
This topic uses events and event handling very little. A number of JavaScript concepts rely on them,
though. For example, keyboard presses and mouse actions all generate events that you should
handle in your games. In this case, you want to execute a function when the audio has finished
playing. Here is the complete play method:
Sound.prototype.play = function () {
if (this.snd === null)
return;
this.snd.load();
this.snd.autoplay = true;
if (!this.looping)
return;
this.snd.addEventListener('ended', function () {
this.load();
this.autoplay = true;
}, false);
};
Finally, you add a property to change the volume of a sound that is playing. This is particularly
useful, because generally you want sound effects to be louder than background music. In some
games, these volumes can be changed by the player (later in the topic, you see how to do that).
Whenever you introduce sound in your game, make sure to always provide volume or at least
mute controls. Games without the ability to mute sounds will suffer the wrath of annoyed users via
reviews! Here is the volume property, which is straightforward:
Object.defineProperty(Sound.prototype, "volume",
{
get: function () {
return this.snd.volume;
},
set: function (value) {
this.snd.volume = value;
}
});
In Painter.js , the file where you load all the assets, you load sounds and store them in a variable,
just as you did for sprites:
var sounds = {};
Search WWH ::




Custom Search