Game Development Reference
In-Depth Information
Chapter 8
Adding Interaction
8.1 Introduction
In the previous chapter, we laid out the basic class structure for the
Painter
game.
We have defined a simple input helper class and a class for representing the game
world. We have already filled part of that game world by adding a background im-
age, a cannon, and doing some basic input handling for changing the color of the
cannon and rotating the cannon barrel. In this chapter, we will add the other game
objects (the ball and the paint cans) to the program and look into how they interact
with each other. For each different kind of game object, we will add a class to the
program.
8.2 The
Ball
Class
8.2.1 Structure of the Class
We will setup the
Ball
class in a very similar fashion as the
Cannon
class. In the
program
Painter5
, you will see a version of the
Painter
game where we added a
ball to the game world. The ball can be shot from the cannon by clicking any-
where in the game screen. Furthermore, the ball changes color together with the
cannon. Just like the
Cannon
class, the
Ball
class will also contain a few
Texture2D
objects to contain the sprite in the three different colors, a sprite pointing to the
current sprite that we want to draw, a color, and a position. However, since the
ball moves, we also need to store its
velocity
. This velocity is a vector that defines
how the position of the ball changes over time. For example, if the ball has a ve-
locity of
(
0
,
1
)
then every second, the
y
-position of the ball will have increased
with 1 pixel (meaning that the ball will fall down). Finally, the ball can be in two
states: it is either flying through the air because it was shot from the cannon, or
it is waiting to be shot (so it is not moving). For that, we add an extra boolean