Game Development Reference
In-Depth Information
protected Texture2D colorRed, colorGreen, colorBlue;
protected Texture2D currentColor;
protected Vector2 position, velocity;
protected Color color;
10.4.4 Access Modifiers and Methods/Properties
Access modifiers such as public or private can also be used on methods and prop-
erties. Just like with member variables, we can control who can call a method or a
property in a class. For example, if we look at the header of the Update method in the
Game class, we see that it is a protected member. This means that the Update method
can only be called by the Game class or any class that inherits from the Game class.
This makes sense, because the Update method forms a part of the game loop, and
we would not want any random class to be able to call this method. So declaring
methods as private or protected helps us to control what level of access a user has to
a class.
In the classes that we have defined so far, all the methods have the public access
modifier, meaning that everyone can access the method. Just like with member vari-
ables, if no access modifier is provided, the compiler assumes that the method is
private .
10.4.5 The Final Cannon Class
We have seen how to construct the Cannon class constructor and how to override the
HandleInput method. As such, the Cannon class is complete (for the complete class,
see Listing 10.1 ). As you can see, the class definition is now much smaller and easier
to read than in the previous version, since all the generic game object members
are placed in the GameObject class. Organizing your code in different classes and
subclasses helps to reduce copying code around and results in generally cleaner
designs. There is a caveat however: your class structure (which class inherits from
which other class) has to be right. Remember that classes should only inherit from
other classes if there is a 'is a kind of' relationship between the classes. To illustrate
this, suppose that we would like to add an indicator at the top of the screen that
shows which color the ball currently is. We could make a class for that and let it
inherit from the Cannon class since it also needs to handle input in a similar way:
class ColorIndicator : Cannon
{
...
}
Search WWH ::




Custom Search