Game Development Reference
In-Depth Information
if
(!exploded)
velocity.Y += 55;
In the
Update
method of the
Level
class, we then check if the timer has reached zero,
and if so, we call the
Explode
method.
if
(timer.GameOver)
player.Explode();
30.3 Drawing Mountains and Clouds
In order to make the level background a bit more interesting, let us add mountains
and clouds to it. We do this in the
Level
constructor. First, let us have a look at how to
add a few mountains. For that, we use a
for
-instruction. In the body of that instruc-
tion, we create a sprite game object, give it a position and add it to the
backgrounds
list. This is the complete
for
-instruction:
for
(
int
i=0;i<5;i++)
{
SpriteGameObject mountain=
new
SpriteGameObject("Backgrounds/spr_mountain_" +
(GameEnvironment.Random.Next(2) + 1), 1);
mountain.Position =
new
Vector2((
float
)GameEnvironment.Random.NextDouble()
∗
GameEnvironment.Screen.X
−
mountain.Width / 2,
−
GameEnvironment.Screen.Y
mountain.Height);
backgrounds.Add(mountain);
}
The first step is to create the sprite game object. Since we have two different moun-
tain sprites, we randomly select one of them using the random number generator.
Then, we calculate the position of the mountain. The
x
position is chosen randomly,
and we use a fixed
y
position so that the mountain is at the appropriate height (we
do not want mountains hanging in the sky). Finally, the mountain object is added to
the
backgrounds
list.
For clouds, we will do something slightly more complicated. We want the clouds
to move from left to right or vice versa, and if a cloud disappears from the screen,
we want a new one to appear. In order to do this, we added a
Clouds
class, which
takes care of this. We create an instance of this class in the
Level
constructor, and
assign it a layer value of two, so that the clouds are drawn in front of the mountains:
Clouds clouds =
new
Clouds(2);
backgrounds.Add(clouds);
Since the
Clouds
class contains a number of moving clouds, it is a subclass of the
GameObjectList
class. Inside the constructor, we use a
for
-instruction to create a num-
ber of clouds and add them to the list. Each cloud is given a random position and a