Game Development Reference
In-Depth Information
10.5.2 The
Reset
Method
When the ball object is reset, it needs to be placed at the start position, the
shooting
variable should be set to
false
, and its velocity should be set to zero, and for
completeness, we set the color to blue. We could override the
Reset
method from
GameObject
as follows:
public override void
Reset()
{
Color = Color.Blue;
position =
new
Vector2(65, 390);
velocity = Vector2.Zero;
shooting =
false
;
}
However, we are again copying code from the
ThreeColorGameObject
class and we
argued a few pages ago that copying code is generally a bad idea. The problem here
is that we do not only want to override the
Reset
method, we want to
extend
it. What
we actually would like to do is to first call the original
Reset
method defined in
ThreeColorGameObject
, and then set the start position and velocity of the ball and its
shooting
status. But how do we call the 'original version' of the
Reset
method if it is
overridden? Here, the
base
keyword proves its use again.
10.5.3
base
Versus
this
The
base
keyword can be used in a similar way to the
this
keyword. As you recall,
this
refers to the current instance that the method is being called on. Similarly,
base
also refers to the current instance, but it
refers to the part of that instance that forms
the base class
. So in our example,
base
refers to the
ThreeColorGameObject
instance
that is a part of the
Ball
instance. This means that if we want to call the version of the
Reset
method that is a part of the
ThreeColorGameObject
class, we can call it through
the
base
instance as
base
.Reset()
.The
Reset
method in the
Ball
class then becomes
public override void
Reset()
{
base
.Reset();
position =
new
Vector2(65, 390);
velocity = Vector2.Zero;
shooting =
false
;
}
So, first the part of the instance representing
ThreeColorGameObject
is reset, and then
we perform the reset operation specific to the ball (setting it at a particular position
and setting the shooting status to
false
).