Search code examples
c++keypressclocksfml

How do I get time elapsed since key pressed in SFML?


So I am working on a game using SFML, and I know there is a function isKeyPressed(key), which returns type bool.

However I am in need of a way to get the time pressed since the key was first pressed, returning an integer representing the number of milliseconds since that key was first pressed (0 if not currently pressed).

Does such a function exist? If not how would I go about writing one, perhaps using the sf::Clock feature?


Solution

  • You would just need to listen for key press events (sf::Event::KeyPressed) and start some sort of timer : store the current time in a sf::Clock and retrieve the elapsed time with getElapsedTime().

    Here is how to listen to events :

    sf::Event event;
    sf::Clock clock;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::KeyPressed) {
            // A key was pressed, start your sf::Clock
            clock.restart();
        }
    }
    // ...
    clock.getElapsedTime();
    

    If you want key specific clocks, you need to specify if you want to treat every key like this, many of them, or few.

    Edit (from your comment) : If you want to treat every key, you will need an array of sf::Keyboard::KeyCount sf::Clock's. Then you can restart clocks of each key independently. Something like this :

    sf::Event event;
    std::array<sf::Clock, sf::Keyboard::KeyCount> keyClocks;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::KeyPressed) {
            // A key was pressed, start this key sf::Clock
            keyClocks[event.key.code].restart();
        }
    }
    // ...
    keyClocks[sf::Keyboard::A].getElapsedTime();
    

    Be aware that if you access a key clock which corresponding key has not been pressed, you might get some weird uninitialized stuff, or maybe the time since the declaration of keyClocks.

    PS : I would personally use the standard library time points and durations because I have not played a lot with SFML, but it does about the same thing. Also, there might be errors in my codes since I have not touched SFML for quite a while.