Stack Overflow Stack Overflow - 25 days ago 7
C++ Question

Make keystate fire only fire once

I'm coding a menu and use

keyState[SDL_SCANCODE_KEY]
to detect when a key is pressed in a cycle like this:

if (Button1 && keyState[SDL_SCANCODE_DOWN])
{
Button1 = false;
Button2 = true;
}
else if (Button2 && keyState[SDL_SCANCODE_DOWN])
{
Button2 = false;
Button3 = true;
}
else if (button3 && keyState[SDL_SCANCODE_DOWN])
{
//and so on
}


The problem with this setup however is that when the user presses the down key the keystate fires multiple times keeping the conditions for button 2 to switch to button 3 active and so on. So how do I make the keystate fire only once, or at least fix this problem? thanks.

Answer

This happens because your system (CPU) runs too fast. To avoid it, You can use either timer or delay.

To simply solve, you can use delay. At the end, Try

delay(1000); // which means delay 1000 clock cycles.