Game Development Reference
In-Depth Information
Now take a look at the following code fragment:
function JewelJamGameWorld(layer) {
GameObjectList.call(this, layer);
this.add(new SpriteGameObject(sprites.background, ID.layer_background));
var rows = 10, columns = 5;
var grid = new JewelGrid(rows, columns, ID.layer_objects);
grid.position = new Vector2(85, 150);
grid.cellWidth = 85;
grid.cellHeight = 85;
this.add(grid);
for (var i = 0; i < rows * columns; i++) {
grid.add(new Jewel());
}
}
JewelJamGameWorld.prototype = Object.create(GameObjectList.prototype);
This is part of the code needed to re-create the hierarchy of the Jewel Jam game. The
JewelJameGameWorld
class inherits from
GameObjectList
. As a result, you can add game objects to
the game world using the
add
method!
First you add a sprite game object that represents the background. You assign the layer
ID.layer_
background
to this object. Then, you create a
JewelGrid
at the
ID.layer_objects
layer (discussed
later in more detail). Finally, you fill this grid with
Jewel
objects. This way, you create a hierarchy of
related game objects that are automatically drawn in the right order! Furthermore, because you dealt
with calling the other game-loop methods as well, you don't have to think about this anymore when
you create the hierarchy.
A Grid of Game Objects
Just as you created a class
GameObjectList
to represent a list of game objects, you can also create
a class
GameObjectGrid
to represent a
grid
of game objects. There is, however, a big conceptual
difference between these two classes. For one thing, the
GameObjectList
class says nothing about
the positions of the game objects it contains. On the other hand,
GameObjectGrid
relates all the game
objects to a grid, which in turn means they all have a position on the grid. But each game object also
has a
position
member variable.
Positions seem to be stored in duplicate, but in fact the positions of game objects in the world
aren't necessarily always the same as the positions where they belong on the grid. The positions
dictated by the grid can be considered
anchor positions
of the game objects (the positions where
they belong). The
actual
positions of the game objects can be different, though. By using the anchor
position in combination with the actual game-object position, you can achieve nice motion effects,
where game objects move smoothly over the grid while still belonging to certain grid positions. An
example of a game where this kind of effect is used quite a lot is
Tetris
: the player can move the
blocks to different positions on the grid, but because the grid anchor position is different from the
actual game-object position, the blocks move smoothly. If you run the
JewelJam3
example, you can
also see a demonstration of this effect if you drag one of the rows to the left or to the right using your
mouse or your finger (on a device with a touch screen).
Search WWH ::
Custom Search