Game Development Reference
In-Depth Information
To get started more easily, you can copy a few classes from the previous game. First you need
the
GameObject
class and the
GameObjectList
class. You also need the basic classes you wrote
for programming games, such as
Keyboard
,
Touch
,
Mouse
,
Game
,
Canvas2D
,
Vector
, and so on. You
modify the
SpriteGameObject
class so it can deal sheets of sprites. Just as in the Jewel Jam game,
a class represents the game world; in this case, the class is called
PenguinPairsGameWorld
. In the
constructor method of that class, you load a background image:
this.add(new SpriteGameObject(sprites.background_level, ID.layer_background));
You also add the penguin sprite to the game world and position it somewhere in the middle of
the screen:
this.penguin = new SpriteGameObject(sprites.penguin, ID.layer_objects);
this.penguin.position = new Vector2(500, 420);
this.add(this.penguin);
Loading a Sprite Sheet
In the Jewel Jam game, a
SpriteGameObject
instance keeps a reference to the sprite, which is
represented by an object of type
Image
. To deal with sprite sheets, you create a new class called
SpriteSheet
that you use instead of an
Image
object directly. You add specific functionality to this
class that allows you to maintain the number of rows and columns in the sheet and that can select
a different element of the sheet to be drawn. In the
loadAssets
method, both the background and
penguin sprites are loaded; and you use the
SpriteSheet
class there, as you can see in the body of
the
loadAssets
method:
Game.loadAssets = function () {
var loadSprite = function (sprite) {
return new SpriteSheet("../assets/sprites/" + sprite);
};
sprites.background_level = loadSprite("spr_background_level.jpg");
sprites.penguin = loadSprite("spr_penguin@4x2.png");
};
The name of the penguin sprite (
spr_penguin@4x2.png
) is peculiar. This is because you use a trick in
the
SpriteSheet
class that lets you specify the dimensions of the sprite sheet in the
file name
. In this
case, the penguin sprite has four columns and two rows. The
SpriteSheet
constructor analyzes the
name of the sprite and determines the dimensions accordingly. There are three possibilities:
The image is a single sprite
: In that case, no definition is provided at the end of
the file name. For example:
spr_wall.png
.
The image is a strip of sprites
: In that case, you provide a single integer number
The image is a sheet of sprites
: Both dimensions (columns and rows) are
provided in the file name. For example:
spr_penguin@4x2.png
.
Search WWH ::
Custom Search