Game Development Reference
In-Depth Information
from the list, and because the object is not part of the list anymore, its parent is set
to
null
.
We can now profit from the layered drawing mechanism we have created, as
well as the hierarchical structure. For example, take a look at the following code
fragment:
gameWorld =
new
GameObjectList();
Texture2D background = Content.Load<Texture2D>("spr_background");
gameWorld.Add(
new
SpriteGameObject(background));
GameObjectList playingField =
new
GameObjectList(1);
playingField.Position =
new
Vector2(85, 150);
gameWorld.Add(playingField);
Here is a part of the code needed to recreate the hierarchy of the
Jewel Jam
game.
We first create a
GameObjectList
instance. Then, we add a
SpriteGameObject
instance
with layer 0 to this list. After that, we create another
GameObjectList
instance called
playingField
, but with layer index 1. As a result, the playing field will be drawn on top
of the background. Because
playingField
is, again, a list of game objects, we can add
more game objects to it. In this way, we create a hierarchy of related game objects
that are automatically updated and drawn in the right order!
14.4.3 A Grid of Game Objects
Just like we created a class
GameObjectList
for representing a list of game objects,
we can also create a class
GameObjectGrid
for representing a
grid
of game objects.
There is, however, a big conceptual difference between these two classes. For one,
the
GameObjectList
class says nothing about the positions of the game objects that it
contains. The
GameObjectGrid
class, on the other hand, relates all the game objects
to a grid, which in turn means that they all have a position on the grid. However,
each game object itself also has a
position
member variable. So how should we deal
with this?
Actually, this is not really a problem, but a feature (where did we hear that be-
fore?). The positions dictated by the grid can be considered as 'anchor positions'
of the game objects (or: the positions to where they belong). The
actual
positions
of the game objects can be different, though. By using the anchor position in com-
bination with the actual game object position, we 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 can be used quite
a lot is Tetris: the player can move the Tetris 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. Also in the program
JewelJam3
, this effect is
demonstrated.