Home > Software engineering >  Getting keyboard input in SDL2 outside of the main game loop
Getting keyboard input in SDL2 outside of the main game loop

Time:01-01

This is my main game loop.

    while (running)
    {
        window.Clear();
        sceneManager.Update(&event);
        window.SetColor(23, 23, 23, 255);

        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                running = false;
            }
        }
        window.Display();
    }

I want to detect keyboard input in my class called 'Scene'. To do this, I attempted to pass in the SDL_Event object to my scene manager every frame, which would then pass it to my scene where I could detect input. When I press a key, nothing is printed. I am wondering how I could correctly get input in a separate class outside of my main loop.

Scene.cpp:

    
void LoadingScene::Update(SDL_Event* event)
{
    rain.Update();
    text.Update();

    if (event->type == SDL_KEYDOWN) 
    {
        cout << "Keydown" << endl;
    }
    

}

CodePudding user response:

scene manager should be called within the event loop

Like this

while (running)
    {
        window.Clear();
        window.SetColor(23, 23, 23, 255);

        while (SDL_PollEvent(&event))
        {
         
       sceneManager.Update(&event);
            if (event.type == SDL_QUIT)
            {
                running = false;
            }
        }
        
        window.Display();
    }
  • Related