Search code examples
c++sfmlgame-development

Function gets called multiple times


So, inside the game loop function that tracks user input is called multiple times. I guess this happens because game loop goes like 40 iterations each second and if I hold down the key for a 0.5 second, function gets called 20 times. I tried to handle this with sfml events too but it didn't work window.setKeyRepeatEnabled(false). How can I solve this?

//this gets called 20-30times
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
    leftPlayerPoints++;
}

Solution

  • Use two boolean flags: One for checking if the key is pressed or not, and one that is used to check if the action have happened yet.

    In short something like

    if (key_is_pressed)
    {
        if (!action_have_happened)
        {
            // Perform action...
            action_have_happened = true;
        }
        // Else: Action have already happened this key-press, don't do it again
    }
    

    When the key is released reset both flags (to false).