Game Development Reference
In-Depth Information
The condition is always placed in parentheses. A block of instructions follows, enclosed by braces.
In this example, the background is drawn only if the mouse's x-position is larger than 200. As a
result, if you move the mouse too far to the left on the screen, the background isn't drawn. You can
place multiple instructions between the braces if you want:
if (Game.mousePosition.x > 200) {
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
cannon.draw();
}
If there is only one instruction, you may omit the braces to shorten the code a bit:
if (Game.mousePosition.x > 200)
Canvas2D.drawImage(sprites.background, { x : 0, y : 0 }, 0,
{ x : 0, y : 0 });
In this example, you want to change the color of the cannon barrel only when the player presses the
R, G, or B key. This means you have to check whether one of these keys is currently pressed. Using
the
Keyboard
object, the condition that checks whether the R key is pressed is given as follows:
Keyboard.keyDown === 82
The
===
operator compares two values and returns true if they're the same or false otherwise.
On the left side of this comparison operator is the value of the
keyDown
variable in the
Keyboard
object. On the right side is the key code that corresponds to the R key. You can now use it in an
if
instruction as follows, in the
update
method of
cannon
:
if (Keyboard.keyDown === 82)
cannon.currentColor = sprites.cannon_red;
A slightly annoying thing is that you have to remember all these key codes in order to understand
what is happening in the program. You can make life easier by defining a second variable called
Keys
that contains the most common key codes, as follows:
var Keys = {
A: 65, B: 66, C: 67, D: 68, E: 69, F: 70,
G: 71, H: 72, I: 73, J: 74, K: 75, L: 76,
M: 77, N: 78, O: 79, P: 80, Q: 81, R: 82,
S: 83, T: 84, U: 85, V: 86, W: 87, X: 88,
Y: 89, Z: 90
};
Now, if you want to know which number the key R has, you can simply access the variable
Keys.R
,
and the
if
instruction becomes a lot clearer:
if (Keyboard.keyDown === Keys.R)
cannon.currentColor = sprites.cannon_red;
Search WWH ::
Custom Search