Game Development Reference
In-Depth Information
We have talked about objects before and we have already seen quite a few ex-
amples of them. For instance, each sprite that is loaded is represented by an ob-
ject of type
Texture2D
.Wehavea
spriteBatch
object that can draw sprites on the
screen. One purpose of these objects is to group data that belong together. For ex-
ample, the
Texture2D
objects will contain all the pixels in the sprite that it represents.
The
SpriteBatch
object will contain all the data needed to draw things on the screen.
The
Painter
object will contain all the data needed for the 'Painter' game. These data
are represented in the objects by
variables
. And if we want to access these variables
from another object, we can do that by using
properties
such as the
Width
property
in the
Texture2D
class.
In addition to data, objects also have
behavior
. This behavior is encoded in the
methods. For example, the behavior of a
Painter
object is mainly encoded in the
Update
and
Draw
methods, which determine how the game behaves. A
SpriteBatch
object has several
Draw
methods that allow the object to do what it needs to do.
The methods and properties that an object knows determine how the data inside
the object are changed. For example, the
HandleInput
method in the
Painter
object
changes the color of the cannon based on player input.
7.3.2 Objects in the
Painter
Game
It actually is quite logical to try and structure the game world into different
objects
,
where each object corresponds to an object in the game. Which objects are present
in the
Painter
game? We have three cans that fall down, a ball, and a cannon. Because
C# is an
object-oriented
language, we can represent these game objects also as
objects in our code.
In C#, the blueprints for objects are
classes
. Therefore, we need to add a class for
each kind of object we have in our game. As a first step, let us add a class
Cannon
that represents the cannon object in the game.
7.3.3 Adding Classes to Your Project
It is very easy to add a class in the Visual C# development environment. Right-click
on the project that you want to add a class to and select
Add
→
Class
. You will see the
window depicted in Fig.
7.1
. Select the 'Class' template and choose an appropriate
name for the class. We will start with a class for the cannon game object, and call
it
Cannon
. In order to do that, choose
Cannon.cs
for the name of the file. After you
have clicked on 'Add', you will see that a new file called
Cannon.cs
has been added
to your project. Double click on that file to open it. The contents of the file will look
like this: