Handling Key Repeats with GetKeyboardState(NULL)

Hi all,
I’m on Ubuntu 18.04 LTS using SDL2.0.10.

I’m logging a keypress like so:

u8 const *keyboard_state = SDL_GetKeyboardState(NULL);

// NOTE: vsync'd
bool want_to_run = true;
while (want_to_run) {
  SDL_Event event = {0};  
  while (SDL_PollEvent(&event)) {
    if (event.type == SDL_QUIT) {
      want_to_run = false; 
    }
    bool move_up = (event.key.repeat == 0 && keyboard_state[SDL_SCANCODE_W])
    // ...
  }
}

When I press the ‘w’ key a single time, it is recorded 5 times. I know a way to overcome this is to record the key presses myself with various bool flags, however I was wondering if there was a way to do this using the information SDL has recorded.

Thanks.

Keypresses are passed to your program via the SDL_KEYDOWN event. You will only receive one such event for each keypress, unless it is held down long enough for the key-repeat mechanism to kick in (and there is a flag to indicate that it is a repeat). See here for more details.

Hi, @rtrussell. I was aware of that method however I was trying to do something more streamlined, i.e a ‘one-liner’. I tried this method and still got the same issue:

  if (event.type == SDL_KEYDOWN) {
    switch (event.key.keysym.sym) {
      case SDLK_w: {
        input.move_up = (event.key.repeat == 0);
      } break;
    } 
  }
  if (event.type == SDL_KEYUP) {
    switch (event.key.keysym.sym) {
      case SDLK_w: {
        input.move_up = false;
      } break;
    } 
  }