Hello!

Let’s explore conditions in Game Maker. Conditions can be created using if/else or switch statements. Let’s try both options.

If/Else

In Game Maker if/else conditions are the same as in other programming languages. The block itself looks like this:

if (<expression>)
{
    <statement>;
}
else
{
    <statement>;
}

For example, we can check the health of our object. If hp < 0, we destroy the object. In order to do this, we will use a new type of event called Step. This event is executed every frame. Usually, the main game logic happens in this event.

First, we set the initial amount of hp in the Create event

hp = 100

Then add event Step with the following code in it. In parentheses next to if is our condition. Where we check if hp is less than 100. In addition to <= less or equal, there is also < less than, > greater than, = equal to, not equal to, !=, >= greater or equal to. You can also use more than one condition at once, for this there is && which means and and || which means or. You can write both symbols or letters in the code. And it can look like this if (hp <= and armor <= 0)

If our condition returns False because the number of hp is greater than 0, we go to else. In else, we simply move our object diagonally and subtract 1 hp. If condition is checked every frame and after a few seconds the number of hp will be less than 0 and the object will be destroyed.

if (hp <= 0) {
	instance_destroy()
}
else {
	x = x + 1
	y = y + 1
	hp = hp - 1
}

If we need to use several conditions, we can use else if. For example, if there is less than 50 hp left, add another object

if (hp <= 0) {
	instance_destroy()
}

else if (hp <= 50) {
	instance_create_layer(x, y, "Instances", obj_vars)
}
else {
	x = x + 1
	y = y + 1
	hp = hp - 1
}

If there are many conditions, then it is better to use switch.

Switch

This is what a switch looks like

switch (<expression>)
{
    case <constant1>:
        <code>
    break;

    case <constant2>:
        <code>
    break;

    // more cases (with breaks)

    default:
        <code>;
}

For example, we can perform some action depending on which key is pressed. In the parentheses next to the switch, we specify keyboard_key, which is a built-in parameter that takes a value depending on which key is pressed. And then we describe each case. If the up key is pressed, we move the hero up, if down, then down, and so on

switch (keyboard_key)
{
    case vk_left:
        x -= 4;
    break;

    case vk_right:
        x += 4;
    break;

    case vk_up:
        y -= 4;
    break;

    case vk_down:
        y += 4;
    break;
}

There may also be a default action in the case, it is performed if all other cases returned false.

Video