Game Development Reference
In-Depth Information
4.2.9 Scope of Variables
The place where we declare a variable has consequences on where we are allowed
to use this variable. Take a look again at the variable
red
in the
DiscoWorld
program.
This variable is declared (and assigned a value) in the
Update
method. Because it is
declared in the
Update
method, we are only allowed to use it in this method. We are
not allowed for example to use this variable again in the
Draw
method. Of course, we
could declare another variable called
red
inside the
Draw
method, but it is important
to realize that the
red
variable declared in
Update
would not be the same
red
variable
declared in the
Draw
method. Alternatively, if we declare a variable at the
class body
level, then we can use it in the
entire class
. We need to use the background color
in both the
Update
and
Draw
methods, because in the
Update
method, we update this
background color, and in the
Draw
method, we use the updated color to paint the
window using the
Clear
method. Therefore, the variable needs to be declared at the
class level, so that all methods in the class can use this variable.
The places where a variable can be used are also called the
scope
of a variable. In
this example, the scope of the variable
red
is the
Update
method, and the scope of the
variable
background
is the
DiscoWorld
class. More officially, the scope of a variable is
determined by the braces that enclose the declaration. In the case of the variable
red
,
these braces are the delimiters of the
Update
method body. In the case of the variable
background
, the braces are the delimiters of the
class body
.
4.2.10 Setting the Background Color
After we have updated our color in the
Update
method, we can pass it as a parameter
to the
Clear
method, which we call in the
Draw
method:
GraphicsDevice.Clear(background);
Try executing the program by pressing F5. You will see that the color changes from
black to red, stays red for a while, then turns from red to black again, and so on.
The
Update
and
Draw
methods are executed a number of times per second, and every
time we look at what the current passed game time is, and we use the milliseconds
component to create a color. This number of milliseconds starts with the value 0 (in
the beginning of the game) and then rises to 1000. Once this value has been reached,
the seconds counter is increased, and the milliseconds counter is reset to 0. Since
we use the milliseconds counter to create the
R
value of the background color, we
see the color changing on the screen.
You have probably noticed that the color stays red for a while, before starting
from black again. Why is this? Remember that the range of RGB value is between
0 and 255? Since the milliseconds counter goes from 0 to 999, we are probably
creating colors like
new
Color(260, 0, 0)
,
new
Color(378, 0, 0)
,or
new
Color(956, 0, 0)
.
What happens when the color is created is that if the R value exceeds its maximum