Apparently, some buttons don’t work anymore when used with GetKeyboardState - I had the same code working not too long ago. I’m on Arch Linux, using sdl2_compat - is this a bug of the distribution?
const Uint8 *state = SDL_GetKeyboardState(NULL);
if (state[SDL_GetScancodeFromKey(1073741906)] && (KeyCooldowns[KeyN]<=0))
{
KeyCooldowns[KeyN]=KeyCooldown;
std::cout << "This will work" << std::endl;
}
if (state[SDL_GetScancodeFromKey(8)] && (KeyCooldowns[KeyN]<=0))
{
KeyCooldowns[KeyN]=KeyCooldown;
std::cout << "This will not work" << std::endl;
}
if (state[SDL_GetScancodeFromKey(1073741882)] && (KeyCooldowns[KeyN]<=0))
{
KeyCooldowns[KeyN]=KeyCooldown;
std::cout << "This neither?" << std::endl;
}
Scancodes represent positions on the keyboard so if you care about the actual key, not the position, then it makes sense to use SDL_Keycode and SDL_GetScancodeFromKey. For example, SDL_SCANCODE_A correspond to the Q key on an AZERTY keyboard so using SDL_SCANCODE_A when you want the A key (regardless of where it is located) is wrong.
Using named constants is a good idea, but use the keycode constants in that case.
E.g. state[SDL_GetScancodeFromKey(SDLK_UP)]
instead of state[SDL_GetScancodeFromKey(1073741906)).
The pointer returned is a pointer to an internal SDL array. It will be valid for the whole lifetime of the application and should not be freed by the caller.
A array element with a value of true means that the key is pressed and a value of false means that it is not. Indexes into this array are obtained by using SDL_Scancode values.
Many games just want to treat a keyboard not as a way to input text, but just as a joystick that has a lot of buttons. The well-known “WASD” key pattern for FPS games is a fine example of this: you want the physical location of a key, regardless of what symbol is printed on the key. After all, on a French keyboard, instead of “WASD”, you’d press “ZQSD”, and on a Hiragana keyboard “てちとし”. Same locations on the keyboard, totally different symbols.
For these, you want SDL_Scancodes: these are guaranteed to reference the physical location on the keyboard and not what is printed on it.
Specifically, they assume a US English QWERTY keyboard layout, no matter what the keyboard in use actually has at that location, but that’s okay because here we just want physical location of the key, not its meaning.
The Specific Key
Some games might want to know the symbol on a key. This tends to be a “press ‘I’ to open your inventory” thing, and you don’t really care where the ‘I’ key is on the keyboard.
This is also useful for looking for the ESC key to cancel an operation, or Enter to confirm, etc; it doesn’t matter where the key is, you still want that key.
These are SDL_Keycodes. They name specific keys and don’t care where on the user’s keyboard they actually are.