user3720596
user3720596

Reputation: 153

C++ & SDL: SDL event repeats endlessly

I have this code which is a part of a simple SDL-based game:

    SDL_PollEvent(&event);
    switch (event.type){
        case SDL_QUIT:
            quit = true;
            break;

        case SDL_KEYDOWN: //Det här är för när en knapp trycks ner...
            switch (event.key.keysym.sym){
                case SDLK_RIGHT:  
                    player1.x_vel = 5.5;
                    std::cout<<"OOOO\n";
                    break;

                case SDLK_DOWN:
                    player2_sprite.src.x = 58;
                    break;
            }

            break;

        case SDL_KEYUP: //Det här är för när en knapp släpps upp..
            switch (event.key.keysym.sym){
                case SDLK_UP:
                    std::cout<<"haaaaa\n";
                    if(player1.canJump){
                        player1.y_vel = -7.5;
                        player1.canJump = false;
                    }
                    break;

                case SDLK_DOWN:
                    std::cout<<"BBBB\n";
                    player2_sprite.src.x = 0;
                    break;
            }

            break;
    }

Now, upon the release of the UP or DOWN arrow key, the release-event keeps triggering forever until any other event is handled. What am I doing wrong here?

Upvotes: 0

Views: 261

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You should be checking the return value of SDL_PollEvent. It returns 1 if there is an event to handle, and 0 if there is not. Normally, you handle events in a loop like this (copied from the documentation here):

while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
         // handle your event here
    }
    // do some other stuff here -- draw your app, etc.
}

What is probably happening in your case, is you are handling the event even when SDL_PollEvent returns 0. The event object is left unmodified in that case, so you keep handling the most recent event over and over.

Upvotes: 3

Related Questions