Game Development Reference
In-Depth Information
The additional advantage here is that using this layout, it's a lot easier to see which cases are
handled by the instructions. You can also see that the example code uses multiple alternatives to
handle the three different color cases in the update method of the cannon object:
if (Keyboard.keyDown === Keys.R)
cannon.currentColor = sprites.cannon_red;
else if (Keyboard.keyDown === Keys.G)
cannon.currentColor = sprites.cannon_green;
else if (Keyboard.keyDown === Keys.B)
cannon.currentColor = sprites.cannon_blue;
Next to the if instruction, there is an instruction called switch that is better suited for dealing with
many different alternatives. See Chapter 21 more information about how to use switch .
Toggling the Cannon Barrel's Behavior
As a final example of using the if instruction to handle mouse button presses, let's try to handle a
mouse button click instead of a mouse button down. You know how to check with an if instruction
whether the mouse button is currently down, but how do you find out whether the player has clicked
(pressed the button while it was not previously pressed)? Look at the program Painter2a. In this
program, the cannon barrel's 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 you only know the current status of the mouse in
the update method. This isn't enough information to determine when a click happens, because a
click is partly defined by what happened the previous time you were in the update method. You can
say that a player has clicked the mouse button if these two things happen:
Currently, the mouse button is down.
update method.
You add an extra Boolean variable leftPressed to the Mouse object, which hat indicates whether a
mouse pressed occurred. You need to set this variable to true if you receive a mouse down event
(covering the first item in the bullet list) and the variable Mouse.leftDown is not yet true (which
corresponds to the second bullet item). This is what the extended handleMouseDown event handler
looks like:
The mouse button was not down during the last call to the
function handleMouseDown(evt) {
if (evt.which === 1) {
if (!Mouse.leftDown)
Mouse.leftPressed = true;
Mouse.leftDown = true;
}
}
 
Search WWH ::




Custom Search