Game Development Reference
In-Depth Information
the background to be drawn before the playing field is drawn, otherwise, the player
will only see the background.
It would be nice if we can indicate somehow as a part of the game object when
it should be drawn. One way to do this is to introduce layers . We can assign a layer
to each game object, and the layer which they have been assigned determines when
the object should be drawn. We can represent these layers in a very simple way by
using integers. Lower layer numbers indicate that the object will be drawn earlier.
So, we could assign layer 0 to the background sprite game object, and layer 1 to
the playing field game object, making sure that the background is drawn before the
playing field. Storing a layer is done directly in the GameObject class by using an
integer variable:
protected int layer;
A minor drawback of using layers is that there is no guarantee about the order in
which objects in the same layer are drawn. So as a programmer, if you want that one
object is always drawn after another, that object has to be in a higher layer.
For a complete view of the GameObject class, see the code in the JewelJam3 exam-
ple. Of course, simply adding a layer member variable to the GameObject class is not
enough, we have to do something with this information. In the next section, we will
have a look at a few different game object subclasses. One of these classes is the
GameObjectList class, which is a class that consists of multiple other game objects.
In this class, we will show how the layer variable can be used to draw the objects in
the right order.
14.4 Different Kinds of Game Objects
14.4.1 A Sprite Game Object
One of the most commonly appearing game objects is a sprite with a position and a
velocity. Since the position and velocity are two member variables available already
in the GameObject class, we can inherit from this class and then we only have to
add a single member variable to store the sprite. In the constructor of this class we
have to pass the sprite as a parameter. Because we are inheriting, we have to call the
constructor of the base class so that the GameObject part of the object is constructed
as well. This constructor expects an integer value denoting the layer. Finally, we
have to override the Draw method. This method is empty in GameObject , because
we decided that game objects do not necessarily have a sprite attached to them.
Inside the overridden Draw method, we draw the sprite on the screen, and we use the
GlobalPosition property to calculate the actual position of the sprite on the screen. For
the complete class, see Listing 14.1 .
 
Search WWH ::




Custom Search