Turning any library's "isKeyPressed" function into "keyPressedOnce"?

896 views Asked by At

Many multimedia libraries in C++ have function to detect keyboard states. But those functions are defective because they only detect if a key is held, and sends a constant signal. I want to turn a function like this to sends one pulse of signal, only when the key is pressed itself, not while it is held after pressing it.

I did something like this (in pseudocode):

while isKeyPressed { if not isKeyPressed (exit_loop) }

This is not effective because even though it works, it is impossible to test for other keys, while the "while" loop is working, and it also delays the program for how long the key is held.

Can anyone think of a better option?

(By the way I used SFML's function sf::Keyboard::isKeyPressed()).

1

There are 1 answers

0
Mario On

Just because some library doesn't exactly work like you want doesn't make it defective. It might be intentional (as in this case).

SFML provides you two different approaches to getting keyboard input (three, if you consider the sf::Event::TextEntered event a different approach):

  • You can check the keyboard state directly to determine whether a key is pressed or not.
  • You can check your window's event queue to detect keys being pressed or released.

While you utilized the first approach, you'd actually want to use the second one:

sf::Event event
while (window.pollEvent(event) {
    switch (event.type) {
        case sf::Event::KeyPressed:
            std::cout << "down: " << event.key.code << std::endl;
            break;
        case sf::Event::KeyReleased:
            std::cout << "up: " << event.key.code << std::endl;
            break;
        // Don't forget to check for other events here
    }
}

As you'll notice, these events will only fire once you press or release the key (unless you're using sf::Window::setKeyRepeatEnabled() to change this behavior), which exactly fits what you're looking for.