Search code examples
c++inputsdl-2

How to get persistent input in SDL2 c++


So I noticed that when getting input with SDL_GetKeyboardState(NULL), when holding a specific button, it is going to first write outlets say a, and after 1 second its gonna continue aaaaaaaa normally. I want to when I hold the button a that it automatically goes aaaaaa. Here is a video if you don't understand my poor explanations: https://streamable.com/oub0w3

There is a delay between it writes out first a, and writing out aaaaa about 1 second. How can I change that? (I want there to be no delay)

Here is my code:

while (gameRunning) {
    SDL_Event event;
    const Uint8* keystates = SDL_GetKeyboardState(NULL);
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            gameRunning = false;
        }
        if (keystates[SDL_SCANCODE_W]) {
            entities[0].setY(entities[0].getY() - 1);
        }
        if (keystates[SDL_SCANCODE_S]) {
            entities[0].setY(entities[0].getY() + 1);
        }
        if (keystates[SDL_SCANCODE_A]) {
            entities[0].setX(entities[0].getX() - 1);
        }
        if (keystates[SDL_SCANCODE_D]) {
            entities[0].setX(entities[0].getX() + 1);
        }
}

Solution

  • You're misusing SDL_GetKeyboardState(nullptr).

    It should be used in the main loop, not in the event loop:

    while (gameRunning)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
                gameRunning = false;
        }
        const std::uint8_t *keystates = SDL_GetKeyboardState(nullptr);
        if (keystates[SDL_SCANCODE_W])
            entities[0].setY(entities[0].getY() - 1);
        if (keystates[SDL_SCANCODE_S])
            entities[0].setY(entities[0].getY() + 1);
        // An so on...
    }