Game Development Reference
In-Depth Information
Suppose you want to have the angle reset to zero after the player releases the left mouse button.
You could add another if instruction, like this:
if (!Mouse.leftDown)
cannon.rotation = 0;
For more complex conditions, this kind of solution will become harder to understand. There is a
nicer way of dealing with this situation: by using an if instruction with an alternative . The alternative
instruction is executed when the condition in the if instruction is not true; you use the else keyword
for that:
if (Mouse.leftDown) {
var opposite = Mouse.position.y - this.position.y;
var adjacent = Mouse.position.x - this.position.x;
cannon.rotation = Math.atan2(opposite, adjacent);
} else
cannon.rotation = 0;
This instruction does exactly the same thing as the previous two if instructions, but you only have
to write the condition once. Execute the Painter2 program and see what it does. Note that the angle
of the cannon barrel is zero as soon as you release the left mouse button.
The syntax of the if instruction with an alternative is represented by the syntax diagram in Figure 6-2 .
The body of an if instruction can consist of multiple instructions between braces because an
instruction can also be a block of instructions, as defined in the syntax diagram in Figure 6-3 .
if instruction
if
(
expression
)
instruction
else
instruction
Figure 6-2. Syntax diagram of the if instruction
block
{
instruction
}
declaration
Figure 6-3. Syntax diagram of a block of instructions (which itself is in turn an instruction)
 
 
Search WWH ::




Custom Search