Game Development Reference
In-Depth Information
public Cannon(ContentManager Content)
You can recognize that this is a constructor method and not a normal method because
of two things:
the name of the constructor method is the same as the name of the class;
constructor methods never have a return type, not even void .
Multiple constructor methods— You may notice that we used the plural
form: constructor methods . It is possible to define multiple constructor meth-
ods in the same class, but only if they have different kinds of parameters,
otherwise the compiler does not know which constructor to use when you
create an instance. This can be useful when you want to offer different ways
of constructing an instance of your class. For example, the Vector2 type of-
fers a constructor without parameters, a constructor with a single parameter
which is assigned to both the x and y values of the vector, and a constructor
that takes two parameters.
It is possible in C# to define a class without providing a constructor
method, as you will see later on. In that case, the compiler will automatically
add a default constructor . This constructor does not have any parameters, and
does not do anything. However, as soon as you add your own constructor to
the class the default constructor will be gone. So if your class has a single
constructor method with one parameter, using that constructor method will be
the only way to create an instance of that class.
Since the Cannon constructor contains a parameter, we need to provide the value
of this parameter when the cannon object is created. This value is available here as
the Content property. In the LoadContent method of the Painter class, we have access to
that property since Painter is an extension of Game . So, we retrieve the content man-
ager using the Content property, and pass it as a parameter to the Cannon constructor
in order to create the cannon instance:
cannon = new Cannon(Content);
Inside the constructor method of the Cannon class, we need to tell the compiler
how to create the Cannon object. One thing that needs to be done is the loading of
the sprites using the content manager that was passed as a parameter. We can do this
with a sequence of instructions:
this .cannonBarrel = Content.Load<Texture2D>("spr_cannon_barrel");
this .colorRed = Content.Load<Texture2D>("spr_cannon_red");
this .colorGreen = Content.Load<Texture2D>("spr_cannon_green");
this .colorBlue = Content.Load<Texture2D>("spr_cannon_blue");
Next to assigning values to the sprite member variables, we also need to add the
instructions that give the remaining variables an initial value. For one, we need to
Search WWH ::




Custom Search