Game Development Reference
In-Depth Information
if
(mouse.X > 200)
spriteBatch.Draw(background, Vector2.Zero, Color.White);
In our example, we want to update the cannon barrel angle only when the player
presses the left mouse button. This means that we have to check if the state of the
left mouse button currently is pressed. This condition is given as follows:
mouse.LeftButton == ButtonState.Pressed
The
==
operator compares two values and returns
true
if they are the same, and
false
otherwise. On the left hand side of this comparison operator, we find the left mouse
button state. On the right hand side, we find the state
ButtonState.Pressed
. So, this
condition checks whether the left button is currently pressed. We can now use it in
an
if
-instruction as follows in the
Update
method:
if
(mouse.LeftButton == ButtonState.Pressed)
{
−
double
opposite = mouse.Y
barrelPosition.Y;
−
double
adjacent = mouse.X
barrelPosition.X;
angle = (
float
)Math.Atan2(opposite, adjacent);
}
So, only if the left mouse button is pressed, we calculate the angle and store its value
in the
angle
member variable. In order to see this program working, run the
Painter1a
example in the solution belonging to this chapter.
6.3 Boolean Values
6.3.1 Comparison Operators
The condition in the header of an
if
-instruction is an expression that returns a truth
value: 'yes' or 'no'. When the outcome of the expression is 'yes', the body of the
if
instruction is executed. In these conditions you are allowed to use comparison
operators. The following operators are available:
•
<
smaller than
•
<=
smaller than or equal to
•
>
larger than
•
>=
larger than or equal to
•
==
equal to
•
!=
not equal to
These operators may be used between two numbers. On the left hand side and the
right hand side of these operators you may put constant values, variables, or com-
plete expressions with additions, multiplications and whatever you want, provided