Game Development Reference
In-Depth Information
Now let us go back to the Cannon constructor. We need to pass the content man-
ager to the constructor so that we can load all the sprites. So, we can initially write
down the header of this constructor as follows:
public Cannon(ContentManager Content)
Inside the constructor, we have to load the different sprites and assign them to the
member variables, just like we did in the original class. However, we also wrote part
of that code in the ThreeColorGameObject constructor. That is because this constructor
is responsible for creating the ThreeColorGameObject part of the Cannon instance.
How can we tell the compiler that the constructor of the base class should be called?
Have a look at the following code:
public Cannon(ContentManager Content)
: base (Content.Load<Texture2D>("spr_cannon_red"),
Content.Load<Texture2D>("spr_cannon_green"),
Content.Load<Texture2D>("spr_cannon_blue"))
{
...
We use the keyword base to denote that we call the constructor of the base class of
this class, in other words: the class that we are inheriting from. We will see another
use of this keyword later on. Because the constructor of the ThreeColorGameObject
class expects three Texture2D object parameters, we call the Content.Load method
to load the sprites and pass them along as a parameter. The body of the Cannon
constructor consists only of setting the position and loading the cannon barrel sprite:
this .cannonBarrel = Content.Load<Texture2D>("spr_cannon_barrel");
position = new Vector2(72, 405);
The rest of the work (assigning the three color sprites and resetting the object) is
done for us inside the ThreeColorGameObject constructor!
10.4.2 Overriding Methods from the Base Class
Now that we have written the constructor of the Cannon class, we have to think
about how a cannon is different from a generic three color game object. As we
have seen initially, the ThreeColorGameObject class has an empty method body for
the HandleInput method, whereas the cannon needs to change its color depending on
the user input. This means that we need to replace the original method from the
ThreeColorGameObject class with a method specific for cannon input handling. We
can also say that we want to override the HandleInput method. Suppose that we add
the following method to the Cannon class:
Search WWH ::




Custom Search