0
\$\begingroup\$

I'm using SDL2 in my game engine and I'm trying to figure out how I can prevent having a monolithic control statement like this:

while (SDL_PollEvent(&event)) {
    switch (event.type) {
        case SDL_KEYDOWN:
            switch (event.key.keysym.sym) {
                case SDLK_w:
               // Move player forward
                // if debug mode move camera forward
                // if in menu navigate the ui
            }
            break;
        case SDL_QUIT:
            running = false;
            break;

    }
}

For the sake of readability and length I kept it short, but basically having a case for every key I might want to use say ~10 and each might do multiple different things depending on the state of the game plus the plethora of other events I feel like it'll spiral out of control and become a big blob of ugly/messy code.

Looking for any suggestions on what I could do to approach this problem or if there's any typical solutions.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ You already figured out a great way to do this: by invoking your own events based on the SDL events, and handling your own events elsewhere: gamedev.stackexchange.com/questions/210586/…. If you're looking for something more maintainable in the long term (e.g. to support rebinding keys), you could also consider the Command Pattern: gameprogrammingpatterns.com/command.html \$\endgroup\$
    – Kevin
    Commented May 3 at 0:44
  • 1
    \$\begingroup\$ See also gamedev.stackexchange.com/questions/190070/… gamedev.stackexchange.com/questions/89755/… \$\endgroup\$
    – Kevin
    Commented May 3 at 0:48
  • \$\begingroup\$ @Kevin oh my bad I didn't even realize I was logged into the wrong account. To be honest I don't actually know why I have two accounts with the same name haha. \$\endgroup\$
    – Konjointed
    Commented May 3 at 1:25
  • 1
    \$\begingroup\$ Obligatory reminder that keycodes (event.key.keysym.sym and SDLK_w) will do the wrong thing on non-QWERTY keyboards, prefer event.key.keysym.scancode and SDL_SCANCODE_W. \$\endgroup\$ Commented May 3 at 12:23
  • \$\begingroup\$ @Konjointed If you accidentally created two accounts, you can go here to merge them. \$\endgroup\$
    – Pikalek
    Commented May 3 at 14:41

0

You must log in to answer this question.

Browse other questions tagged .