Game Development Reference
In-Depth Information
We would like to design our classes in such a way that they can be used in many
different games. In the last version of the game Jewel Jam , the row selector object
interacts with the grid object. We have achieved this by passing the grid object as a
reference to the row selector object, so that the row selector can directly access any
information it needs from the grid. However, this is not an ideal solution either. Once
game objects start to become more complex, we would have to pass many different
parameters to the constructors of these objects, making them overly complicated
and difficult to manage. What we need is a way to find objects in the game world,
without making the game world rely on code specific to our game.
16.2.2 Assigning Identifiers to Game Objects
One way of solving this problem in a more generic way is to assign identifiers to
our game objects. Not all of the objects need identifiers, generally only the ones
that interact with other objects do. In our example, we have chosen to use strings
as identifiers for game objects. Although this may not be the most performance-
efficient approach, it is very easy to implement, as well as easy to understand for
humans. After all, “pass me the salt, please” is a lot easier to grasp than “pass me
the object with id 4815162342, please”. All we need to do is extend our game object
classes so that we can assign an identifier to them. We will start with the GameObject
class. In this class, we add a member variable to store its ID:
protected string id;
In order to store an id when we create a game object, we also add a parameter to the
GameObject constructor. The header then becomes
public GameObject( int layer = 0, string id = "")
Because not all game objects need an ID, we have set the empty string as a de-
fault value. Inside the constructor, we assigned the parameter value to the member
variable. We also add a property ID to have easy access to the ID of a game object:
public string ID
{
get { return id; }
}
Because all game objects inherit from the GameObject class, this means that they
will now also have an identifier. In many cases, we have to update the constructor of
the GameObject subclasses so that they pass along the identifier to the constructor of
the base ( GameObject ) class. For example, the updated SpriteGameObject constructor
is given as follows:
Search WWH ::




Custom Search