Game Development Reference
In-Depth Information
Loading Game Assets the Right Way
In order to make sprite loading a little bit easier, let's add a method
loadSprite
to the
Game
object:
Game.loadSprite = function(imageName) {
var image = new Image();
image.src = imageName;
return image;
}
The code for loading the different sprites now becomes much shorter:
var sprFolder = "../../assets/Painter/sprites/";
sprites.background = Game.loadSprite(sprFolder + "spr_background.jpg");
sprites.cannon_barrel = Game.loadSprite(sprFolder + "spr_cannon_barrel.png");
sprites.cannon_red = Game.loadSprite(sprFolder + "spr_cannon_red.png");
sprites.cannon_green = Game.loadSprite(sprFolder + "spr_cannon_green.png");
sprites.cannon_blue = Game.loadSprite(sprFolder + "spr_cannon_blue.png");
However, the problem of dealing with the time it takes to load sprites is not solved yet. In order to
tackle this problem, the first thing you need to do is keep track of how many sprites you're loading.
You do this by adding a variable to the
Game
object, called
spritesStillLoading
:
var Game = {
spritesStillLoading : 0
};
Initially, this variable is set to the value 0. Every time you load a sprite, you increment the variable by 1.
Logically, you do this in the
loadSprite
method:
Game.loadSprite = function(imageName) {
var image = new Image();
image.src = imageName;
Game.spritesStillLoading += 1;
return image;
}
So now, every time you load a sprite, the
spritesStillLoading
variable is incremented. Next you
want to
decrement
this variable every time a sprite has finished loading. This can be done by using
an event-handler function. You assign this function to the variable
onload
in the
image
object. In the
body of that function, you decrement the variable. Here is the version of the
loadSprite
method that
adds the event handler:
Game.loadSprite = function (imageName) {
var image = new Image();
image.src = imageName;
Game.spritesStillLoading += 1;
image.onload = function () {
Game.spritesStillLoading -= 1;
};
return image;
};
Search WWH ::
Custom Search