Game Development Reference
In-Depth Information
7.4 The
Cannon
Class
7.4.1 Data in the
Cannon
Class
The goal of the
Cannon
class is to group the data and behavior belonging to the can-
non game object together. In the
Painter3
example, there were a few member vari-
ables associated with the cannon: the variable containing the cannon barrel sprite,
three variables containing the different color indication discs, another
Texture2D
vari-
able to maintain the current color, and variables for storing the position, origin and
angle of the cannon barrel. We are going to put all these member variables inside
the
Cannon
class, since they are all belong with the cannon
game object
:
Texture2D cannonBarrel;
Texture2D colorRed, colorGreen, colorBlue;
Texture2D currentColor;
Vector2 position;
Vector2 barrelOrigin, colorOrigin;
Color color;
float
angle;
We have also added a member variable
color
to indicate the current color of the can-
non. Although this variable is redundant, it will be convenient later on for retrieving
and setting the current cannon color.
Now that we have added these declarations to our
Cannon
class, every time we
create an instance of this class, the object that has been created will contain these
variables. However, we did not yet provide any information about which
values
these variables should have when the object is created. For this, we need to define a
constructor
method in the class. The constructor method is a special kind of method
that tells the compiler what to do when an object of type
Cannon
is created. Often,
constructor methods will mainly contain instructions for assigning values to the
variables that are a part of the object. Not all of these values are known inside of the
Cannon
class. For example, we need to assign a value to the
cannon_barrel
variable.
Normally, we would load the sprite using the
Content
property. However, we cannot
do that inside the
Cannon
class, because there is no
Content
property in that class.
So how can we access the content manager in this case? Fortunately, constructors
can have
parameters
just like other methods. The variable that the
Content
property
gives us is of type
ContentManager
, so we add a parameter to the
Cannon
constructor
of that type. In order to use the
ContentManager
type, we have to add an additional
using
-instruction at the top of the
Cannon.cs
file, so that the compiler can recognize
the type:
using
Microsoft.Xna.Framework.Content;
The header of the
Cannon
constructor method is then defined as follows: