Game Development Reference
In-Depth Information
Scope of Variables
The place where you declare a variable has consequences for where you're allowed to use the
variable. Look at the variable
d
in the MovingSquare program. This variable is declared (and assigned
a value) in the
update
method. Because it's declared in the
update
method, you're only allowed to
use it in this method. For example, you aren't allowed to use this variable again in the
draw
method.
Of course, you could declare another variable called
d
in the
draw
method, but it's important to
realize that the
d
variable declared in
update
would in that case not be the same
d
variable declared
in the
draw
method.
Alternatively, if you declare a variable at the
object
level, you can use it anywhere, as long as you put
the name of the object in front of it. You need to use the x-position of the rectangle in both the
update
and
draw
methods, because in the
update
method, you update this position, and in the
draw
method,
you use it to draw a rectangle at that x-position. Therefore, it's logical that this variable needs to be
declared at the object level, so that all methods belonging to the object can use the variable.
The places where a variable can be used are together called the variable's
scope
. In this example,
the scope of the variable
d
is the
update
method, and the scope of the variable
Game.rectanglePosition
is the global scope.
What You Have Learned
In this chapter, you have learned:
How to store basic information in memory using variables
How to create objects that consist of member variables and methods
update
method to change the game world through variables and
the
draw
method to display the game world on the screen
How to use the
Search WWH ::
Custom Search