Game Development Reference
In-Depth Information
somehow refer to 'the object we are currently manipulating'? In C#, and many other
object-oriented programming languages, this is done by the keyword
this
, which
always refers to the object we are currently manipulating. So, the graphics device is
created as follows:
graphics =
new
GraphicsDeviceManager(
this
);
The object that
this
refers to is in this case the object that is stored in the variable
game
that we declared in the
Main
method. We can use the
this
keyword in many
different cases. It is sometimes also useful to clarify that we are explicitly manip-
ulating the object, instead of some unrelated variable. For example, we could also
write the following instruction to set the content root directory:
this
.Content.RootDirectory = "Content";
By explicitly writing
this
in front of the
Content
property, we clarify that we are
accessing a property called
Content
and that this property manipulates the current
object.
5.3.5 Properties: Retrieving or Changing Parts of an Object
Next to methods, we have seen that a class can also define
properties
. Properties
are a way to access the data inside an object. Some of these properties allow only
reading these data, other properties also allow you to write these data. For example,
the
Texture2D
class has properties called
Width
and
Height
that we can use to retrieve
the width and the height of a sprite. These two lines of code retrieve the width and
the height of the balloon sprite and store them in two local variables of type
int
:
int
width = balloon.Width;
int
height = balloon.Height;
The
Width
and
Height
properties are
read-only
. We are not allowed to change them,
which makes sense, because they reflect the size of the loaded sprite.
Vector2
also
has properties, namely
X
and
Y
. Look at the following example:
Vector2 v =
new
Vector2(3,4);
int
xval = v.X;
v.Y = 12;
As you can see in this example, the
X
and
Y
properties can be read from as well
as written to. After we have constructed the
Vector2
object, we retrieve the
x
-value
by using the
X
property. We set the
y
-value of the vector by using the
Y
property.
Changing the value that a property represents is done by regular assignment, just
like normal variables.