Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SDL_KEYDOWN triggering twice

Tags:

c++

sdl-2

I am following lazy foo's tutorial, however I realized every time I press press s or p, SDL_KEYDOWNtriggers twice. How can this be fixed?

Here is the code snippet:

while(SDL_PollEvent(&e) != 0) {
    if(e.type == SDL_QUIT) {
        quit = true;
    }
    else if(e.type == SDL_KEYDOWN) {
        if(e.key.keysym.sym == SDLK_s) {
            if(timer.isStarted()) {
                timer.stop();
                printf("stop\n");
            }
            else {
                timer.start();
                printf("start\n");
            }
        }
        else if(e.key.keysym.sym == SDLK_p) {
            if(timer.isPaused()) {
                timer.unpause();
                printf("unpause\n");
            }
            else {
                timer.pause();
                printf("pause\n");
            }
        }
    }
}

Pressing s once:

start
stop
like image 487
drum Avatar asked Sep 11 '25 19:09

drum


1 Answers

TL;DR: Check if e.key.repeat equals to 0 before handling the events.


SDL generates fake repeated keypresses if you hold a key long enough. This is used mostly for text input.

The original key press has .repeat == 0, and fake presses have .repeat == 1.

For convenience reasons probably (I'd argue that it's rather inconvenient), since SDL 2.0.5 the actual key press generates two events instead of one. One has .repeat set to 0, and other (new) one has it set to 1.

like image 116
HolyBlackCat Avatar answered Sep 13 '25 09:09

HolyBlackCat