0
\$\begingroup\$

I'm currently using SDL_GetKeyboardState to capture key states once per frame. This works great for input that I want to handle for as long as a key is pressed (i.e character movement) but creates a real problem when I want to respond to a key press only once while the key is held down. Currently, even a rapid key press+release occurs over 2-3 frames, meaning the input is handled that many times instead of just once.

In short, is there a simple way to handle input once when a key is pressed, and then ignore that key until it's released and pressed again?

Just to mention, I've already looked at using event.key.repeat to see if a key has been repeated, but this only seems to work when the key has been pressed for a certain period of time (in my case 10+ frames)

Thanks in advance

\$\endgroup\$
2
\$\begingroup\$

The usual way to process most input is to set up your game loop to poll for events. For your specific case: set a flag on the SDL_KEYDOWN event for the key you want to listen to. When you want to process the input, check if the flag is set and if it is, do your action and unset the flag. Example:

// ... main loop initialization

bool left_down = false;
SDL_Event event;

while(SDL_PollEvent(&event)){
switch(event.type){
    // look for a keypress
    case SDL_KEYDOWN:
        if(event.key.keysym.sym == SDLK_LEFT){
            left_down = true;
        }
        break;
    }
}

// ... main loop stuff

// ... later (in some entity's update() function?)
if(left_down == true) {
    // do whatever
    left_down = false;
}

I couldn't find a great tutorial for this for SDL2, but I don't think the API for this has changed much since SDL 1.2, so you can most likely take a look at some tutorial on events for 1.2 and still follow along. Here's the documentation on SDL_PollEvent.

\$\endgroup\$
  • \$\begingroup\$ Sorry for the long delay in accepting your answer! I don't know why I hadn't thought of creating a simple flag long before now. Thanks again :) \$\endgroup\$ – Triforcer Oct 15 '14 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.