Game Development Reference
In-Depth Information
if
(age<4)
spriteBatch.Draw(babyPlayer, playerPosition, Color.White);
else if
(age<12)
spriteBatch.Draw(youngPlayer, playerPosition, Color.White);
else if
(age<65)
spriteBatch.Draw(adultPlayer, playerPosition, Color.White);
else
spriteBatch.Draw(oldPlayer, playerPosition, Color.White);
Behind every
else
(except the last one), there is another
if
-instruction. For babies,
the
babyPlayer
sprite is drawn, and the rest of the instructions are ignored (they are
behind the
else
after all). Old players on the other hand, go through all the tests
(younger than 4? younger than 12? younger than 65?) before we conclude that we
have to draw the
oldPlayer
sprite.
We used indentation in this program to indicate which
else
belongs to which
if
. When there are many different categories, the text of the program becomes less
and less readable. Therefore, as an exception to the usual rule that instructions after
the
else
should be indented, we allow for a simpler layout with such complicated
if
-instructions.
if
(age<4)
spriteBatch.Draw(babyPlayer, playerPosition, Color.White);
else if
(age<12)
spriteBatch.Draw(youngPlayer, playerPosition, Color.White);
else if
(age<65)
spriteBatch.Draw(adultPlayer, playerPosition, Color.White);
else
spriteBatch.Draw(oldPlayer, playerPosition, Color.White);
The additional advantage here is that using this layout, it is a lot easier to see which
cases are handled.
6.4.3 Toggling the Cannon Barrel Behavior
As a final example of using the
if
-instruction to handle mouse button presses, let us
try to handle a mouse button
click
instead of a mouse button press. We know how to
check with an
if
instruction if the mouse button is currently pressed, but how do we
find out if the player has clicked (meaning pressing and then releasing the mouse
button)? Have a look at the program
Painter1c
. In this program, the cannon barrel
rotation follows the mouse pointer after you click the left button. When you click
again, the cannon stops following the mouse pointer.
The issue with this kind of 'toggle' behavior is that we only know the current
status of the mouse in the
Update
method. This is not enough information for deter-
mining when a 'click' happens, because a click is partly defined by what happened
the previous time we were in the
Update
method. We can say that a player has clicked
the mouse button if these two things happen: