Game Development Reference
In-Depth Information
Locating Sprites
Before a program can use any kind of assets, it needs to know where to look for those assets. By
default, the browser acting as interpreter looks for sprites in the same folder as the JavaScript file.
Look at the SpriteDrawing example belonging to this chapter. You see a file called
spr_balloon.png
in the same folder as the HTML file and the JavaScript file. You can load this sprite and draw it on
the screen.
Loading Sprites
Let's now look at how you can load a sprite from a file. Once you have done this, you store it
somewhere in memory by using a variable. You need this variable in several different game-loop
methods. In the
start
method, you load the sprite and store it in the variable. In the
draw
method,
you can access the variable in order to draw the sprite on the screen. Therefore, you add a variable
called
balloonSprite
to the
Game
object. Here you can see the declaration of the
Game
variable and
its initialization:
var Game = {
canvas : undefined,
canvasContext : undefined,
balloonSprite : undefined
};
In the
start
method of
Game
, you assign values to these variables. You have already seen how to
retrieve the canvas and the canvas context. Just like
Game
, the canvas and canvas context are
objects
that each consist of other variables (or objects). If you load a sprite, you have
an object that represents
the sprite
. You could define an object variable that contains all the information in the image:
Game.balloonSprite = {
src : "spr_balloon.png",
width : 35,
height : 63,
...
}
This becomes problematic when you want to load hundreds of sprites for your game. Every time, you
would have to define such an object by using an object literal. Furthermore, you would have to make
sure you don't accidentally use other variable names in the object, because then you would have an
inconsistent representation of images. Fortunately, you can avoid this trouble by using
types
.
A type is basically a definition of what an object of that type should look like; it's a
blueprint
for an
object. For example, JavaScript knows a type called
Image
. This type specifies that an image object
should have a width, a height, a source file, and more. There is a very simple way to create an object
that has the
Image
type, using the
new
keyword:
Game.balloonSprite = new Image();
Search WWH ::
Custom Search