Game Development Reference
In-Depth Information
8.3.3 Calculating a Random Velocity and Color
Each time a can falls down, we want to create a random velocity and color for it.
We can use the random variable to help us do this. Let us first look at creating a
random velocity. For neatness, we are going to do this in a separate method inside
the PaintCan class called CalculateRandomVelocity . We can then call this method when
we want to initialize the velocity of the can. Because we express velocity as an
object of type Vector2 ,the return value of this method is of the same type. Here
we will use the member variable minVelocity to define the minimum velocity that
paint cans have when they fall down. This variable is given an initial value in the
constructor method:
minVelocity = 30;
We use this minimum velocity value when we calculate a random velocity, which
we do in the CalculateRandomVelocity method:
public Vector2 CalculateRandomVelocity()
{
return new Vector2(0.0f, ( float )Painter.Random.NextDouble()
30 + minVelocity);
}
As you can see, the return type of this method is indeed Vector2 . The method contains
only a single instruction, which returns a new Vector2 object, with an x -velocity of
zero and a y -velocity that is calculated using the random number generator. Because
the random number generator creates a value of type double , we need to explicitly
convert it to a value of type float so that we can store it in a Vector2 object. After that,
we multiply it by 30 and add the value stored in the member variable minVelocity in
order to get a positive y -velocity between minVelocity and minVelocity+30 .
For calculating a random color, we also use the random number generator, how-
ever we do not use the NextDouble method but the Next method. This method gives an
integer value, and we can specify a maximum value or a range of possible values.
For example, the call Painter.Random.Next(10) will give a random number between
0 and 9 (so 10 is excluded). By using an if -instruction, we can then select a color
based on the randomly generated number. This is what the method looks like:
public Color CalculateRandomColor()
{
int randomval = Painter.Random.Next(3);
if (randomval == 0)
return Color.Red;
else if (randomval == 1)
return Color.Green;
else
return Color.Blue;
}
Search WWH ::




Custom Search