Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SDL 2.0 Key repeat and delay

I'm having a problem with SDL 2.0 keyboard input in pong-like game. When I order to move to the left by pressing left arrow, it is processed by SDL_PollEvents() and responds correctly if the key was pressed once. However, if I keep the key pressed, I get a short delay (as long as Windows key repeat delay) before moving continuously.

Here is function processing events:

void Event::PlayerEvent (Player &player)
{
    while (SDL_PollEvent (&mainEvent))
    {
        switch (mainEvent.type)
        {
            case SDL_KEYDOWN :
                switch (mainEvent.key.keysym.sym)
                {
                    case SDLK_ESCAPE :
                        gameRunning = false;
                        break;
                    case SDLK_LEFT :
                        player.moving = player.left;
                        break;
                    case SDLK_RIGHT :
                        player.moving = player.right;
                }
                break;
            case SDL_QUIT :
                gameRunning = false;
        }
    }
}

EDIT: After all, I managed to fix this issue by calling SystemParametersInfo (SPI_SETKEYBOARDDELAY, 0, 0, 0) at the start of the program and SystemParametersInfo (SPI_SETKEYBOARDDELAY, 1, 0, 0) at the end, to return to standard key repeat delay.

like image 641
KVASS Avatar asked Mar 31 '15 16:03

KVASS


1 Answers

For game movement, you would typically not use events, but rather use states.

Try using SDL_GetKeyboardState() outside of the event loop:

const Uint8* keystates = SDL_GetKeyboardState(NULL);

...

if(keystates[SDL_SCANCODE_LEFT])
    player.moving = player.left;
else if(keystates[SDL_SCANCODE_RIGHT])
    player.moving = player.right;
like image 171
Jonny D Avatar answered Sep 20 '22 10:09

Jonny D