drum
drum

Reputation: 5651

SDL_KEYDOWN triggering twice

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

Upvotes: 4

Views: 1491

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96106

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.

Upvotes: 7

Related Questions