Search code examples
c++sdlsdl-2

SDL_KEYUP triggered when key is still down


I am using SDL2 in C++ to create a sprite. However, the SDL_KEYUP is constantly triggered when I am pressing the key.

        void update() override {
            if(Game::event.type == SDL_KEYDOWN) {
                switch(Game::event.key.keysym.sym) {
                    case SDLK_z:
                        cout << "key down" << endl;
                        break;
                    default:
                        break;                    
                }
            }
            if(Game::event.type == SDL_KEYUP) {
                switch(Game::event.key.keysym.sym) {
                    case SDLK_z:
                        cout << "Key up" << endl;
                        break;
                    default:
                        break;                    
                }
            }
        }

Solution

  • It's a feature, not a bug. If you hold a key for half a second or so, SDL will start to generate "fake" key-down & key-up events.

    This is used primarily for text editing, but is mostly useless otherwise.

    Ignore all keyboard events that have event.key.repeat != 0.


    Also, if you're writing a game, you might want to use scancodes instead of keycodes (e.g. event.key.keysym.scancode == SDL_SCANCODE_A instead of event.key.keysym.sym == SDLK_a).

    Keycodes depend on the current layout, and scancodes don't. Scancodes represent physical key locations. The diffence is noticeable if you use a non-QWERTY layout. (E.g. SDLK_z is always bound to the key that has Z printed on it, while SDL_SCANCODE_W is bound to W on QWERTY and Z on AZERTY.)