Game Development Reference
In-Depth Information
Loading Game Assets the Wrong Way
Previously, I talked about the browser loading files in an arbitrary order because these files have to
be retrieved from a server. The same rules apply to loading game assets such as sprites and sounds.
This is the method you've used up until now to load game assets:
var sprite = new Image();
sprite.src = "someImageFile.png";
var anotherSprite = new Image();
anotherSprite.src = "anotherImageFile.png";
// and so on
It seems straightforward. For each sprite you want to load you create an Image object and assign
a value to its src variable. Setting the src variable to a certain value doesn't mean the image is
immediately loaded. It simply tells the browser to start retrieving that image from the server. Depending
on the speed of the Internet connection, this may take a while. If you try drawing the image too soon,
the browser will stop the script because of an access error (trying to draw an image that is not yet
loaded). In order to avoid this issue, this is how the sprites were loaded in the previous example:
sprites.background = new Image();
sprites.background.src = spriteFolder + "spr_background.jpg";
sprites.cannon_barrel = new Image();
sprites.cannon_barrel.src = spriteFolder + "spr_cannon_barrel.png";
sprites.cannon_red = new Image();
sprites.cannon_red.src = spriteFolder + "spr_cannon_red.png";
sprites.cannon_green = new Image();
sprites.cannon_green.src = spriteFolder + "spr_cannon_green.png";
sprites.cannon_blue = new Image();
sprites.cannon_blue.src = spriteFolder + "spr_cannon_blue.png";
cannon.initialize();
window.setTimeout(Game.mainLoop, 500);
Note the last line of code, in bold. After setting the src variables of all the Image objects, you tell
the browser to wait 500 milliseconds before executing the main loop. That way, the browser should
have enough time to load the sprites. But what if the Internet connection is too slow? Then 500
milliseconds might not be enough. Or what if the Internet connection is really fast? Then you're
letting the player wait needlessly. In order to solve this issue, you need the program to wait until all
the images have been loaded before executing the main loop. You will see how to do this properly
with event-handler functions. But before that, let's talk a little bit more about methods and functions.
Methods and Functions
You've already seen and used quite a few different kinds of methods and functions. For example, there
is a clear difference between the Canvas2D.drawImage method and the cannon.update method: the
latter one doesn't have any parameters, whereas the first one does (the sprite, its position, its rotation,
and its origin). Additionally, some functions/methods can have a result value of an object that can be
used in the instruction that does the method call—for example, by storing the result in a variable:
var n = Math.random();
 
Search WWH ::




Custom Search