CDorr
CDorr

Reputation: 9

Application using SDL exiting on any keypress. It shouldn't be though

I cannot figure out how to properly handle key presses with the SDL library.

As of right now, I have the following code:

bool running = true;
SDL_Event event;
while (running) {       
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym){
                case SDLK_RIGHT:
                    buttons.setState(2);
                    SDL_UpdateWindowSurface(window);
                case SDLK_LEFT:
                    buttons.setState(1);
                    SDL_UpdateWindowSurface(window);
                case SDLK_INSERT:
                    if (buttons.getState() == 1){
                        buttons.setState(3);
                        SDL_UpdateWindowSurface(window);
                        SDL_Delay(50);
                        buttons.setState(1);
                        SDL_UpdateWindowSurface(window);
                    }
                    else{
                        if (buttons.getState() == 2){
                            buttons.setState(4);
                            SDL_UpdateWindowSurface(window);
                            SDL_Delay(50);
                            buttons.setState(2);
                            SDL_UpdateWindowSurface(window);
                        }
                        else{ 
                            break;
                        }
                    }
                default:
                    running = true;
                }
            case SDL_QUIT:
                running = false;
                SDL_DestroyWindow(window);
                SDL_Quit();
            break;
            }
        }
    }

There is a Drawable class of which buttons is an instance of. The states are different frames I would like to draw. However, I only want to draw them on the press of the left or right arrow keys. As of now, the program is simply exiting on any key press.

I have no idea where to go from here.

Upvotes: 0

Views: 1052

Answers (2)

HgMerk
HgMerk

Reputation: 91

You forgot break; in every case statement you wrote. Also you could add this :

case SDLK_ESCAPE: <---- so you can also press ESC on keyboard to quit :)

Another thing, SDL_Quit() will handle the window destruction. If you started SDL with SDL_Init() you need not worry about closing the sub-systems. If you explicitly called SDL_VideoInit(), then you must close sub-systems with SDL_QuitSubSystem.

You can also, remove default: Running = true; (after fixing the break;)

Good luck :)

Upvotes: 0

UmNyobe
UmNyobe

Reputation: 22910

case SDL_KEYDOWN: is missing his break statement, which lead every key press to execute the code int the SDL_QUIT case as well. It should be

            default:
                running = true;
            }
        break; <--- inserted
        case SDL_QUIT:

Upvotes: 3

Related Questions