Game Development Reference
In-Depth Information
random
x
velocity. Then, we add an
Update
method to the
Clouds
class, in which we
check if a cloud has exited the screen. Since we need to do this for each cloud game
object, we do this using a
foreach
-instruction that traverses all the game objects in
the list. If a cloud has exited the screen, we create a new cloud object with a random
position and velocity. A cloud can exit the screen either on the left side or on the
right side. If a cloud is positioned outside of the screen on the
left
, and its
x
velocity
is
negative
, we know it has exited the screen. If the cloud is positioned outside of
the screen on the
right
side, and its velocity is
positive
, we also know it has ex-
ited the screen. We can capture these two situations for a cloud
c
in the following
if
-instruction:
if
((c.Velocity.X < 0 && c.Position.X + c.Width < 0) ||
(c.Velocity.X > 0 && c.Position.X > GameEnvironment.Screen.X))
// remove this cloud and add a new one
Removing the cloud is easy:
this
.Remove(c);
Then, we create a new cloud game object:
SpriteGameObject cloud =
new
SpriteGameObject("Backgrounds/spr_cloud_"
+ (GameEnvironment.Random.Next(5) + 1));
We assign an
x
velocity to this cloud, which can be either positive or negative. The
y
velocity of the cloud is always zero, so that the cloud only moves horizontally:
cloud.Velocity =
new
Vector2((
float
)(
(GameEnvironment.Random.NextDouble()
∗
2)
−
1)
∗
20, 0);
Then, we calculate a random cloud height by multiplying the
y
screen resolution
with a random number between zero and one. From that number, we subtract half
of the cloud height to make sure that we never generate a cloud that is drawn fully
below the screen:
∗
float
cloudHeight = (
float
)GameEnvironment.Random.NextDouble()
−
cloud.Height / 2;
GameEnvironment.Screen.Y
We position the cloud either at the left border or the right border of the screen,
depending on the direction in which the cloud is moving:
if
(cloud.Velocity.X < 0)
cloud.Position =
new
Vector2(GameEnvironment.Screen.X, cloudHeight);
else
cloud.Position =
new
Vector2(
−
cloud.Width, cloudHeight);
Now we add the new cloud to the list: