Game Development Reference
In-Depth Information
angle of the cannon barrel. Let us add another property for doing that to the
Cannon
class. This property also has a get and a set part, and we define it as follows:
public float
Angle
{
get
{
return
angle; }
set
{ angle =
value
;}
}
As an exercise, can you make a more secure version of this property, which only
allows angle values between 0 and 2
π
radians? In the
HandleInput
method, we use
this property to update the angle of the cannon:
cannon.Angle = (
float
)Math.Atan2(opposite, adjacent);
For fun, we will do another one. Let us add a read-only property to the
Cannon
class for accessing the position of the cannon:
public
Vector2 Position
{
get
{
return
position; }
}
Since this property only has a
get
part, we cannot modify the data through this
property. For example, the following instruction would result in a compiler error
(try it):
cannon.Position = Vector2.Zero;
As you can see, adding properties to a class is very easy! And they provide a
great means to control how data inside an object is changed from the outside. As an
exercise, can you add a property to the
Cannon
class that allows reading the cannon
barrel sprite? How about writing it? Can you also add a property to the
Painter
class
that gives access to the
spriteBatch
object?
7.4.6 Properties Do Not Always Directly Correspond to Data
The properties that we added to the cannon class correspond directly to member
variables: they get and set the values of the
position
,
color
, and
angle
variables. How-
ever, there is no particular restriction on properties that they can only directly cor-
respond to member variable values. A property may also use one or more member
variables to calculate a
new
value. For example, we could add a property called
Bottom
, which calculates the bottom of the cannon barrel. This (read-only!) prop-
erty would return a
float
value, which is computed every time the property is called.
The header and body of this property would be given as follows: