SFML community forums

Help => General => Topic started by: Surge on April 10, 2017, 01:39:45 pm

Title: How to check if key is double-tapped?
Post by: Surge on April 10, 2017, 01:39:45 pm
Hello. In my game I want the player's character to sprint if I double tap the movement keys. (WASD)

Here is my current movement logic...

void PlayerCharacter::handleInputCurrent(sf::Event& event) {
    int speed = DefaultSpeed;

    setVelocity(sf::Vector2f(0, 0));

    if (event.type == sf::Event::KeyReleased) {
        switch (event.key.code) {
        case sf::Keyboard::W:
            m_state = IdleUp;
            break;

        case sf::Keyboard::S:
            m_state = IdleDown;
            break;

        case sf::Keyboard::A:
            m_state = IdleLeft;
            break;

        case sf::Keyboard::D:
            m_state = IdleRight;
            break;
        }
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
        setVelocity(sf::Vector2f(getVelocity().x, -speed));
        m_state = WalkUp;
    }
   
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
        setVelocity(sf::Vector2f(getVelocity().x, speed));
        m_state = WalkDown;
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
        setVelocity(sf::Vector2f(-speed, getVelocity().y));
        m_state = WalkLeft;
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
        setVelocity(sf::Vector2f(speed, getVelocity().y));
        m_state = WalkRight;
    }
}

By the way, m_state is used for animation purposes and setVelocity(x, y) is used to set the velocity of an entity.

Thanks for reading!  :)
Title: Re: How to heck if key is double-tapped?
Post by: nyenye on April 10, 2017, 03:50:22 pm
Hi! To make it work the way you want you gotta store last time the key was pressed somewhere. Then on the event KeyPressed for that same key, check elapsed time. Maybe you can use unix time?

What I would probably do is make a two key command. WADS to move, and Shift to run.

Good luck!
Title: Re: How to heck if key is double-tapped?
Post by: eXpl0it3r on April 10, 2017, 05:18:19 pm
There's no point in "using unix time", it's not cross platform and with sf::Clock there's no need for it.

As mentioned track the time between two key pressed/released events, if it's small enough, count it as a double tab.