Game Development Reference
In-Depth Information
Before you read on, try and find out what the value is of the variables a , b , and c
after these instructions have been executed. In the first line, we declare and initialize
a boolean a . The truth value that is stored in this boolean is evaluated from the
expression 12 > 5 , which evaluates to true . So, variable a has the value true .Inthe
second line, we declare and initialize a new variable b , in which we store the result
of a more complex expression. The first part of this expression is the variable a ,
which contains the value true . The second part of the expression is a comparison
3+4==8 . This comparison is not true (3
4 does not equal 8), so this evaluates to
false , and therefore the logical 'and' also results in false . Therefore, the variable b
contains the value false .
The third line stores the result of the logical 'or' operation on variables a and b
in variable c . Since a contains the value true , the outcome of this operation is also
true , and it is assigned to c . Finally, there is an if -instruction, which assigns the value
false to variable a , but only if !c evaluates to true , that is, c evaluates to false .Inthis
particular case, c is true , so the body of the if instruction is not executed. Therefore,
after all the instructions are executed, a and c contain the value true , and b contains
the value false .
+
6.4 More on if -Instructions
6.4.1 An if -Instruction with an Alternative
We can use the if -instruction to check if the left mouse button is down. If so, we
update the angle of the cannon barrel:
if (mouse.LeftButton == ButtonState.Pressed)
{
double opposite = mouse.Y
barrelPosition.Y;
double adjacent = mouse.X
barrelPosition.X;
angle = ( float )Math.Atan2(opposite, adjacent);
}
In the Painter1a example, the angle stays the same when the left mouse button is not
pressed. But suppose that we want to have the angle set to zero again once the player
releases the left mouse button. We could add another if -instruction, like this:
if (mouse.LeftButton != ButtonState.Pressed)
angle = 0f;
However, there is a nicer way of dealing with this: by using an if -instruction with
an alternative. The alternative instruction is executed when the condition in the if -
Search WWH ::




Custom Search