Search code examples
c++sdlsdl-imagesdl-3

Recieve input from keyboard in SDL3 inside of the main loop?


I want to make it so hitting keys changes the displayed image on my window but I don't really know how to set that up.

Here is the beginning of the main loop that I am trying to use:

while (!loopShouldStop) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_EVENT_QUIT) {
            loopShouldStop = true;
        }
        else if (event.type == SDL_EVENT_KEY_DOWN) {
            //don't really know what I'm supposed to do here
    }

    SDL_RenderClear(renderer);
    SDL_RenderTexture(renderer, currentImage, NULL, &dstRect);
    SDL_RenderPresent(renderer);
}

Solution

  • You can use a std::map of SDL_Scancodes to collect keyboard state changes during the SDL_PollEvent() loop and then flex on that state while drawing each frame:

    std::map< SDL_Scancode, bool > keyState;
    
    while (!loopShouldStop) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_EVENT_QUIT) {
                loopShouldStop = true;
            } else if (event.type == SDL_EVENT_KEY_DOWN) {
                keyState[event.key.scancode] = true;
            } else if(event.type == SDL_EVENT_KEY_UP) {
                keyState[event.key.scancode] = false;
            }
        }
    
        SDL_RenderClear(renderer);
        if(keyState[SDL_SCANCODE_W]) {
            SDL_RenderTexture(renderer, otherImage, NULL, &dstRect);
        } else {
            SDL_RenderTexture(renderer, currentImage, NULL, &dstRect);
        }
        SDL_RenderPresent(renderer);
    }
    

    The SDL wiki has some other approaches.