Maik Klein
Maik Klein

Reputation: 16158

SDL and GLFW only report one key (repeat) per poll even if multiple keys are held down at the same time

SDL_Event event;
while(SDL_PollEvent(&event)){
    if(event.type == SDL_KEYDOWN || event.type == SDL_KEYUP){
         //...
    }
}

and

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{

}

For example I press W and S at the same time, both libraries report that W and S have been pressed.

But if I continue to hold W and S, only one key will be reported as if the other isn't held down at all.

Also if I hold down W and S and only S is reported and I press another key for example Q both libraries won't report that any key is currently held down at all.

It seems that the keystate repeated for both libraries is pretty much useless.

Is this standard behavior or could it be that it just happens on my system?

Upvotes: 1

Views: 507

Answers (1)

patthoyts
patthoyts

Reputation: 33223

You can use SDL_GetKeyboardState when handling the SDL_KEYUP and SDL_KEYDOWN events to check for the state of more than a single key at a time. The keyboard state holds the current state of all the keys. The SDL_GetModState call should be used for the modifer keys like Ctrl or Shift.

Quick example:

static void keyboard_handler()
{
    int n, count = 0;
    char buf[80];
    const uint8_t *state = SDL_GetKeyboardState(&count);
    buf[0] = 0;
    if (state[SDL_SCANCODE_RIGHT]) strcat(buf, "right ");
    if (state[SDL_SCANCODE_LEFT]) strcat(buf, "left ");
    if (state[SDL_SCANCODE_UP]) strcat(buf, "up ");
    if (state[SDL_SCANCODE_DOWN]) strcat(buf, "down ");
    if (buf[0] != 0)
        printf("%s\n", buf);
}

Running this in response to the SDL_KEYUP and SDL_KEYDOWN events I get multiple words printed when holding down more that 1 arrow key at a time. eg:

left
right left
left up down

Upvotes: 3

Related Questions