Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to check if key is double-tapped?  (Read 1781 times)

0 Members and 1 Guest are viewing this topic.

Surge

  • Newbie
  • *
  • Posts: 3
    • View Profile
How to check if key is double-tapped?
« 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!  :)
« Last Edit: April 12, 2017, 08:37:24 am by Surge »

nyenye

  • Newbie
  • *
  • Posts: 10
    • View Profile
Re: How to heck if key is double-tapped?
« Reply #1 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!

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11029
    • View Profile
    • development blog
    • Email
Re: How to heck if key is double-tapped?
« Reply #2 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/