Game Development Reference
In-Depth Information
set the default color of the cannon to blue. The following two instructions achieve
that:
this
.currentColor = colorBlue;
color = Color.Blue;
We also need to define the position and the origins of the barrel and the color indi-
cator disc, we do this as follows:
barrelOrigin =
new
Vector2(cannonBarrel.Height, cannonBarrel.Height) / 2;
colorOrigin =
new
Vector2(currentColor.Width, currentColor.Height) / 2;
position =
new
Vector2(72, 405);
Now all the member variables of the
Cannon
instance have a value, and the object
creation is complete. Note that we have not assigned a value to the
angle
member
variable explicitly. Because
angle
is of type
float
, which is a primitive type, it gets
assigned a default value of 0 by the compiler.
7.4.2 Adding Methods to the
Cannon
Class
Just like in the
Painter
class, it is possible to add our own methods to the
Cannon
class. A very useful method is one that resets a game object to its initial state. Such
methods are especially useful in games. When the player restarts a game or a level
in a game, we simply reset all the game objects to their initial states by calling the
reset method. In order to provide for this, let us add a method called
Reset
to the
Cannon
class.
The
Reset
method does not have any parameters. It simply sets the member vari-
ables in our class to some initial value. We do not have to reset all the member
variable values, only the ones that will be changed while playing the game. For ex-
ample, we do not have to give the
cannon_barrel
variable an initial value, since it will
not change while playing the game. The
angle
variable, however will change, so we
have to reset it. Also, we have to reset the color, since that may also change while
playing the game. As a result, we add the following
Reset
method to the
Cannon
class:
public void
Reset()
{
currentColor = colorBlue;
color = Color.Blue;
angle = 0.0f;
}
The
Reset
method is an example of a method that
changes
the object that it works
on. This is the general goal of methods: define behavior that modifies the member