Game Development Reference
In-Depth Information
also need to be positioned correctly. Furthermore, what happens if we change the
position of the playing field? We would have to update the position of all the game
objects that hang under it. There is a better way to do this: we have to differentiate
between local and global positions .The global position of a game object is its ab-
solute x - and y -coordinates in the game world. The local position of a game object
is its position with respect to the position of the parent game object. So, do we need
to store both these positions in each game object? No, in fact we only need to store
the local position . We can calculate the global position by adding the local position
of the game object to the position of the parent. If there is no parent, then the local
position is the same as the global position. We can write a property that does this
work for us:
public virtual Vector2 GlobalPosition
{
get
{
if (parent != null )
return parent.GlobalPosition + this .Position;
else
return this .Position;
}
}
Using this property, we can now obtain both the local position of the game object
(which is stored in the position member variable), as well as the global position,
which is accessed through the GlobalPosition property. As you can see, we calculate
the global position by adding the local position to the global position of the parent.
The global position of the parent is, again, calculated by taking its local position
and adding it to the global position from its parent. This goes on, until we reach a
game object that does not have a parent, in which case the local position becomes
the global position. As an example, the global position of the row selection object is
calculated by adding the (local) position of the root object, the local position of the
playing field object plus its own local position. This is exactly the behavior that we
get when we access its GlobalPosition property. It may seem a bit strange that we are
calling the GlobalPosition property inside the GlobalPosition property itself, but this is
perfectly valid C# code. In fact, we are using a programming technique here called
recursion (we will talk more about that later on).
14.3.4 Layers of Game Objects
When we want to draw a game object, we can use the GlobalPosition property as a
convenient way to find out where to draw the game object on the screen. The only
problem is that we do not have any idea in which order the game objects in the
hierarchy should be drawn. When looking at the Jewel Jam game, we clearly want
Search WWH ::




Custom Search