GameMaker Why does one keypress persist through multiple if statement layers?

P

Paymon005

Guest
To exemplify, I have written the code below with an object and placed it within a room.

Create:
state = 0;

Step:
if (state == 0){
if(keyboard_check_pressed(vk_enter)){
state = 1;
if(state == 1){
if(keyboard_check_pressed(vk_enter)){
state = 2;
}
}
}
}

Draw:
if(state == 2){
draw_text(room_width/2,room_height/2,"HELLO WORLD")
}

You should have to press ENTER twice in order for hello world to appear on screen, however one press changes state to 2. If i place a breakpoint within the first if layer and debug, this does not occur. Thanks for any help.
 

Slyddar

Member
keyboard_check_pressed will last through 1 whole step. Otherwise you could have multiple objects with keyboard_check_pressed calls that would fail if it only worked on the first one.
 
P

Paymon005

Guest
keyboard_check_pressed will last through 1 whole step. Otherwise you could have multiple objects with keyboard_check_pressed calls that would fail if it only worked on the first one.
I see, that makes perfect sense. Is there a way to force the code to complete the step or maybe a just a better way to perform what I am trying to do?
 

CloseRange

Member
I see, that makes perfect sense. Is there a way to force the code to complete the step or maybe a just a better way to perform what I am trying to do?
when there is a will there is a way.
Code:
switch(state) {
     case 0:
          state = 1;
          break;
     case 1:
          state = 2;
          break;
}
that should work like you want.

break; is used to end a for statement, while statement, switch statement, and with statement early.

you could also use else if statments if you wanted:

Code:
if(state == 0) {
     state = 1;
} else if(state == 1) {
     state = 2;
} else if(state == 2) {
    // ...
}
 
R

Robzoid

Guest
You used separate if statements (if, if, if) rather than (if, else if, else if). Each "if" will be evaluated.
 

NightFrost

Member
Also note that you can use io_clear() to clean the state of all keyboard and mouse buttons for the check commands. You'd usually need this when you need to prevent a keypress bubbling up through checks in multiple objects, or when you have several mouse-clickables on top of each other and want only one of them to process a click.
 
P

Paymon005

Guest
Thank you all very much for the responses. I decided that switch statements are the best way to format the structure of my code. I’m am not unfamiliar with coding, but I am still trying to understand how GM compiles and executes the code. The fact that one key press persists through a step event was not intuitive to me at all.
 
Top