1
\$\begingroup\$

What is wrong with SDL2 SDL_PollEvent() function? When I press-and-hold a key it enters "while (SDL_PollEvent())" block each frame. If in previous frame event queue was emptied and in new frame I press-and-hold button it should create one event - SDL_KEYDOWN. Run this code. It has macro to compile for SDL2 and SDL1.2. SDL1.2 runs okay, polls keyhold and empies queue. SDL2 seems to pump it back each frame, so SDL_PollEvents grabs the same even next frame.

#define USESDL2

#include <iostream> //cout
using namespace std;

#ifdef USESDL2
//link with -l SDL2
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>

#else
//link with -l SDL
#include <SDL/SDL.h>
#include <SDL/SDL_events.h>

#endif // USESDL2

int main(int argc, char **argv)
{
    bool q = true;
    SDL_Event e;

    SDL_Init(SDL_INIT_VIDEO);
#ifdef USESDL2
    SDL_Window *win;
    win = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
#else
    SDL_Surface *buff;
    buff = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
#endif
    while (q) {
        while (SDL_PollEvent(&e)) {
            cout << "Polling: ";
            switch (e.type) {
            case SDL_QUIT:
                q = false;
            break;
            case SDL_KEYDOWN:
                cout << "Key down: ";
                switch (e.key.keysym.sym) {
                case SDLK_q:
                    q = false;
                break;
                case SDLK_UP:
                    cout << "UP\n";
                break;
                case SDLK_r:
                    cout << "r\n";
                break;
                }
            break;
            }
        }
    }

#ifdef USESDL2
    SDL_DestroyWindow(win);
#endif
    SDL_Quit();
}
\$\endgroup\$
1
  • \$\begingroup\$ SDL2s behavior can vastly differ from SDL1. You should stick with only one of them (i would prefer SDL2). Why do you mix SDL2 and SDL1 at all? I am just curious. \$\endgroup\$ Jul 19, 2018 at 22:00

1 Answer 1

3
\$\begingroup\$

SDL2 actually generates key repeat events automatically. You need to manually filter repeated key events out by checking the repeat member of a SDL_KeyboardEvent. This is something that did not automatically happen in SDL1, so that's why the behaviour is different. See SDL_KeyboardEvent for more info.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .