Game Development Reference
In-Depth Information
The header of the method shows that it returns a value of type Color and that the
method has no parameters. The first line in the body of the method generates a
random integer that is either 0, 1, or 2. We then check with an if -instruction which
of these three numbers was selected and we return the associated color.
Now that we have programmed these two methods for generating random values,
we are going to use them when we define the behavior of the paint can.
8.3.4 Updating the Paint Can
The Update method in the PaintCan class should do at least the following things:
1. set a randomly created velocity and color if the can is currently not yet falling
down,
2. update the can position by adding the velocity to it, and
3. check if the can has fallen down completely and reset it in that case.
For the first task, we can use an if -instruction to check if the can is currently not
moving, e.g. if the velocity equals zero. Furthermore, we want to introduce a bit of
unpredictability for when the can appears. In order to achieve that effect, we only
assign a random velocity and color if some generated random number is smaller
than a threshold of 0 . 01. This means that because of the uniform distribution only
in approximately one out of a hundred random numbers, the number will be smaller
than 0 . 01. As a result, the body of the if -instruction will only be executed sometimes,
even when a can's velocity is zero. Inside the body of the if -instruction, we use the
two methods we defined earlier for generating a random velocity and a random
color:
if (velocity.Y == 0.0f && Painter.Random.NextDouble() < 0.01)
{
velocity = CalculateRandomVelocity();
color = CalculateRandomColor();
}
The next step is to update the can position by adding the current velocity to it, again
taking into account the elapsed game time:
( float )gameTime.ElapsedGameTime.TotalSeconds;;
position += velocity
Now that we have initialized the can and updated its position, we need to handle
the 'special cases'. For the paint can, we have to check if it has fallen outside of
the game world. If so, we need to reset it. The nice thing is that we already wrote
a method for checking if a certain position is outside of the world. This was the
IsOutsideWorld method in the GameWorld class. We can now use that method again to
check if the position of the can is outside of the world. If this is the case, we need to
reset the can so that it is placed at the top outside of the screen again. The complete
Search WWH ::




Custom Search