• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Issue with while loops

J

Jmarlin3

Guest
The purpose of the next few lines is add a number to y to make my object move
GML:
if(keyboard_check_pressed(vk_down)){
    y += movespeed;   
}
The code above works just fine, but when I change it to a while loop:
Code:
while(keyboard_check_pressed(vk_down)){
    y += movespeed;   
}
The goal of the while loop was to constantly apply the movespeed gives to y while the down key is pressed. What am I missing here?
 

sp202

Member
What you want is keyboard_check, a while loop will keep doing that in one step, so the object will likely fly off screen.
 

FrostyCat

Redemption Seeker
Every novice needs to hear this: Loops are for repeating all-at-once. Step events are for repeating over time.

You want the "down arrow key held down" condition monitored over time. while loops are not for you. if checks in the Step event are for you.
GML:
if (keyboard_check(vk_down)) {
    y += movespeed;   
}
A lot of rookies think "while this is happening, do this" and gravitate instantly to while because the wording matches. This is a fatal attraction. Most of the time when they think about this, they should actually be using the Step event.

Also notice that I used keyboard_check(), not keyboard_check_pressed(). The difference between these two are clearly documented:
The Manual entry for keyboard_check() said:
With this function you can check to see if a key is held down or not. Unlike the keyboard_check_pressed or keyboard_check_released functions which are only triggered once when the key is pressed or released, this function is triggered every step that the key is held down for.
The next time you see a function, variable or language keyword, don't just look at the name and make baseless assumptions about what it does. Actually read up on it.
 
Top