Game Development Reference
In-Depth Information
6.2.2 The if -Instruction: Executing an Instruction Depending on a
Condition
As a simple example of how we can use the mouse button state to do something,
let us make a simple extension of the Painter1 program, where we only calculate the
new angle of the cannon barrel if the left mouse button is down. This means that
we have to change the instructions in the Update method, because that is where we
calculate the barrel angle.
Until now, all the instructions we have written had to be executed all the time. For
example, drawing the background sprite and the cannon barrel sprite always needs
to happen. But calculating the barrel angle only has to happen sometimes , namely
when the player presses the left mouse button. In broader terms, we want to execute
an instruction only if some condition holds true. This kind of instruction is called a
conditional instruction , and it uses a new keyword: if .
With the if -instruction, we can provide a condition, and execute a block of in-
structions if this condition holds (in total, this is sometimes also referred to as a
branch ). Examples of conditions are:
1. the number of seconds passed since the start of the game is larger than 1000, or
2. the balloon sprite is exactly in the middle of the screen, or
3. the monster has eaten my character.
These conditions can either be true or false . A condition is an expression , because
it has a value (it is either true or false ). This value is also called a boolean value. It
is associated with a type called bool , which we will talk about more later on. With
an if -instruction, we can execute a block of instructions if a condition is true .Takea
look at this example:
if (mouse.X > 200)
{
spriteBatch.Draw(background, Vector2.Zero, Color.White);
}
This is an example of an if -instruction. The condition is always placed in parenthe-
ses. After that, a block of instructions follows, enclosed by braces. In this example,
the background is only drawn if the mouse x -position is larger than 200. This means
that if you move the mouse too far to the left of the screen, the background is not
drawn anymore. We can place multiple instructions between the braces if we want:
if (mouse.X > 200)
{
spriteBatch.Draw(background, Vector2.Zero, Color.White);
spriteBatch.Draw(cannonBarrel, Vector2.Zero, Color.White);
}
If there is only one instruction, you may omit the braces to shorten the code a bit:
Search WWH ::




Custom Search