Search code examples
c++timersfmlclockpause

How to use a clock within a while loop


i'm coding a game and I've been trying to implement a pause game functionality where when the user presses R the game will pause, and after x time when R is pressed again, the game will resume. I have gotten this to work when user presses R, and when any other key such as M is pressed the game will resume as normal. However, when I assign R to both pause and unpause events, the initial R is detected for both pause and unpause, and the game pauses for a fraction of a second and resumes. I've tried implementing timers and counters inside my pause loop but to no avail. what I really want to do is make it so that the user must wait x amount of time before R is pressed again, this will fix the problem, but I can't get clock.getElapsedTime to work within the loop for some reason. Why is this? here's my current code:

case sf::Keyboard::R:
        pause = true;   
        break;


//pause game
        clock1.restart();
        while (pause)
        {               
            //cout << clock1.getElapsedTime.asSeconds();

            //if (clock1.getElapsedTime.asSeconds() > 1.0)
            //{
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::R))
                    pause = false;
            //}
        }

Solution

  • Try placing sf::sleep(sf::seconds(0.1)); BEFORE your while loop. I had the same problem. Somehow if I would read the value of isKeyPressed() for the same letter consequently it would not change at the time I read it the second time and would assume it's still pressed. Placing a little pause there solved my problem, so try if it does solve it in your case.

    Please tell me if it works, I am interested