Justin
Justin

Reputation:

SDL_event KEYDOWN behavior problem

Here is the problem, I have written an event loop to detect keydown and keyup events. The problem I am running into is that a keydown event is generating a keydown and a keyup event when the key is pressed and held down. I am using the arrow keys to move an object and then to stop moving when the key is released(keyup). Any help would well help. Thanks. =)

Justin

P.S. I would post the code but I can't get it to look right.

print("         SDL_Event event;
    SDL_EnableKeyRepeat(0,0);
    while(SDL_PollEvent(&event)){
        switch(event.type){
        case SDL_QUIT:
            done = true;
            break;
        case SDL_KEYDOWN:
            switch(event.key.keysym.sym){
            case SDLK_ESCAPE:
                done = true;
                break;
            case SDLK_LEFT:
                animate_x = -5;
                cout << "left press\n";
                break;
            case SDLK_RIGHT:
                animate_x = 5;
                break;
            case SDLK_UP:
                animate_y = -5;
                break;
            case SDLK_DOWN:
                animate_y = 5;
                break;
            default:
                break;
            }
            break; -left out in original
        case SDL_KEYUP:
            switch(event.key.keysym.sym){
            case SDLK_LEFT:
                cout << "left up\n";
                animate_x = 0;
                break;
            case SDLK_RIGHT:
                animate_x = 0;
                break;
            case SDLK_UP:
                animate_y = 0;
                break;
            case SDLK_DOWN:
                animate_y = 0;
                break;
            default:
                break;
            }
            break; -left out in original
        }
    }");

While trying to figure out how to post code I noticed that I had left out a default in two of the cases. The code now works. It kept going through the cases and executing the code that matched what was in the queue. Silly me. Thanks for all the help. =)

Upvotes: 3

Views: 3909

Answers (2)

user42056
user42056

Reputation: 71

You might want to use SDL_GetKeyState instead of keeping track of keydown/keyup; I use it for detecting the instant state of keys, which you can use to determine if keys are being held down over successive frames.

Upvotes: 3

Joh
Joh

Reputation: 2380

It looks like you have key repeat enabled. To disable it, use

SDL_EnableKeyRepeat(0, 0);

Upvotes: 3

Related Questions