Game Development Reference
In-Depth Information
Loading Sprites
Now that you have different objects in your game, where do you load the sprites? You could load all
the sprites in the start method of the Game object, but another option is to add a similar method to,
for example, the cannon object and load the sprites belonging to the cannon there. Which approach
is better?
There is something to say for loading the sprites belonging to the cannon object in an initialization
method of that object. That way, you can clearly see from the code which sprites belong to what
object. However, this also means that if you reuse the same image for different game objects, you
have to load that sprite multiple times. And for games that run in a browser, this means the browser
has to download the image file from a server, which can take time. A better option is to load all the
sprites the game needs when the game is started. And to clearly separate the sprites from the rest
of the program, you store them in an object called sprites . This object is declared at the top of the
program as an empty object:
var sprites = {};
You fill this variable with sprites in the Game.start method. For each sprite you want to load, you
create an Image object, and then set its source to the sprite location. Because you're already using
quite a few different sprites, you load these sprites from another asset folder that contains all the
sprites belonging to the Painter game. That way, you don't have to copy these image files for all the
different examples in the topic that use these sprites. These are the instructions that load the various
sprites needed for the Painter2 example belonging to this chapter:
var spriteFolder = "../../assets/Painter/sprites/";
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";
You use the + operator here to concatenate text. For example, the value of the expression
spriteFolder + "spr_background.jpg" is "../../assets/Painter/sprites/spr_background.jpg" .
The sprite folder path looks a bit complicated. The ../../ bit means you're moving up two directories
in the hierarchy. This is needed because the example directories Painter2 and Painter2a are not
at the same level as the assets directory. You store these images in variables that are part of the
sprites object. Later, you access that object when you need to retrieve sprites. The next step is
handling the player's keypresses.
 
Search WWH ::




Custom Search