what is an if statement
if statements are the essential parts of programming. They are conditional statements that allow for events to occur. if you want your character to move, you want to set a conditional statement so that he performs specific actions when required to do so.
The syntax of an if statement involves
- an if
- a condition
- brackets
- what is desired to happen when the condition is met (between the brackets);
A moving code using if statements
if (keyboard_check(vk_left))
{
x -= 5;
}
if (keyboard_check(vk_right))
{
x += 5;
}
if (keyboard_check(vk_up))
{
y -= 5;
}
if (keyboard_check(vk_down))
{
y += 5;
}
if the keyboard key left is held, your character will move to the left by five pixels. That doesn't seem like a lot, but this code must be written in the step event. The step event occurs every frame of the game. Therefore, if your game runs at 30 frames/second, in one second, you will have moved a distance of 150 pixels to the left.
The else "statement"
if you want something to occur if one thing happens and one thing to occur if anything else happens, you can follow the if statement with an else.
Example:
You are rating something inside the game, the player decides a rating.
if (rating > 0 and rating <= 10)
{
draw_text(x,y,"Thank you for taking the time to leave a rating!");
}
else
{
draw_text(x,y,"Please choose a number between 0 and 10");
}
This code requires the player to choose a number between one and ten. If he does, he is met with gratitude, otherwise he will be told he chose a number that is not between 0 and 10, obviously.