I am creating a simple game with HTML5 and JavaScript.
Initially when the Game starts it takes some time to load images and sound.
During this time the user has to wait and the screen looks unpleasant.
So here’s what i want to do
-
Check loading status of images and sound.
-
Increase % of loading as and when resources are loaded and respectively increase progress bar.
I really don’t have any key from where to start. Please Guide me through.
Monitoring load status for all loading items can be daunting, but, in a nutshell, the best way to go about it is to do the following:
First, add to a
totalResourcescounter, so the game knows how many resources to expect.Add
eventListenersto the loading resources, and add to aloadingResourcescounter. If it loads successfully or fails, add to theloadingResourcescounter.Once the counters are equal, either all the resources loaded, or there were some errors in loading certain files.
The catch with this method is, on rare occasions, the
loadingResourcescan match thetotalResourcesvariable prematurely. You can fix this by making a flag that checks to see if all the resources that needed to load have started loading already.Now, depending on how you make your game, a failed resource load shouldn’t really stop the game from working. For example, if a sound doesn’t load properly, it just won’t play. You might want to retry or abort if a resource needs to load.
As for a % based loading, that’s a bit iffy. The HTML5 spec includes a progress bar, but for multiple resources, your best bet might just be a bar that fills up as resources are loaded.
Addendum:
Sound files are a huge pain to load, and I’ve had little success perfecting it across all browsers. Here’s how I went about it:
First, don’t rely on the
load()function to invoke loading anaudioelement. Instead, force it to play, like so:sound.channels[i].volume = 0;sound.channels[i].play();(Also, to replay a sound, set the
durationto a near 0 value when the sound is paused.)As to allow multiple sounds to play at the same time, it is good practice to have multiple audio elements (thus the
channelsarray above). However, you don’t need to wait for all the sound channels to load. Once one loads, clone the node and force a silent play again to avoid any delays.It’s anecdotally more reliable to use the
canplaythroughevent callback to see if a sound is ready. If a sound fails to load, use theerrorcallback. The problem is that there are a number of errors that can cause a sound file to fail to load.Don’t forget to use
<source>elements to allow for multiple audio formats.