Game Development Reference
In-Depth Information
to use the anchor position that we can retrieve from the
GameObjectGrid
to calculate
the velocity of the game object belonging at that position. The effect of this is that
when the game object is not exactly at the anchor position, it automatically starts
moving towards that position.
For doing this, we introduce another class called
Jewel
which represents a game
object inside the grid (in this case a kind of jewel). This game object is a subclass of
SpriteGameObject
. The only thing we need to change in this game object is the
Update
method, since drawing the sprite is already properly handled in the base class.
So what needs to be done in the
Update
method? First we need to find out what the
anchor position of this game object is. We can do this by calling the
getAnchorPosition
from the parent (which normally should be a
GameObjectGrid
instance). However, if
we try the following, the compiler complains:
Vector2 anchorPosition =
this
.Parent.GetAnchorPosition(
this
);
Why? Because
this
.Parent
returns a
GameObject
instance, and the
GameObject
class
does not contain a method called
getAnchorPosition
. What we should do instead is
tell the compiler that the parent game object is in fact a
GameObjectGrid
instance.
This is done through
casting
. Casting is something that we have already seen when
dealing with basic types such as
float
or
string
, but it can also be done with classes.
For example, this is how we can cast a
GameObject
to a
GameObjectGrid
instance:
GameObjectGrid parentGrid = (GameObjectGrid)
this
.Parent;
A problem with doing this occurs in the case when
this
.Parent
is not an instance of
GameObjectGrid
. In this case, the casting operation will cause an exception, which—
if not handled—will result in ending the program. Later on in this topic, in Chap.
25
,
we will discuss exceptions in more detail. There is another way to perform this cast,
by using the
as
keyword::
GameObjectGrid parentGrid =
this
.Parent
as
GameObjectGrid;
This does exactly the same thing as the previous casting operation, except that if
this
.Parent
cannot be casted to a
GameObjectGrid
instance, the result is
null
.This
means that we can check if the cast was successful. If so, we modify the velocity
of the game object so that it moves toward the anchor position, and we update the
object position by calling the
Update
method of the base class:
if
(parentGrid ==
null
)
return
;
Vector2 targetPosition = parentGrid.GetAnchorPosition(
this
);
velocity = (targetPosition
−
position)
∗
8;
base
.Update(gameTime);
As you can see, we calculate the velocity by taking the difference between the target
position (which equals the anchor position), and the current position. In order to get