SFML community forums

Help => System => Topic started by: glu4it on November 15, 2013, 04:27:19 pm

Title: pause in a game
Post by: glu4it on November 15, 2013, 04:27:19 pm
Hi. I'm making a game. And now i want to make a pause. Here my code
while(window.isOpen())
        if(Keyboard::isKeyPressed(Keyboard::Return))
        {
                while(window.isOpen())
                {

                                Event event;
                                while(window.pollEvent(event))
                                {
                                        if(event.type == Event::Closed)
                                                window.close();
                                        else
                                                if (event.type == Event::KeyPressed)
                                                        wait=false;
                                       
                                }
                                if(!wait){
                                               
                               
                                if(Keyboard::isKeyPressed(Keyboard::Escape))
                                {
                                        window.close();
                                }
                               
                               
                                if( Keyboard::isKeyPressed(Keyboard::P))
                                {
                                        wait = true;
                                }

                        window.display();
                  }

           }
 
So, after I press P in game, it stop's, I press P again but game still soped. And when I press another key game starts. What am I doing wrong?
PS Sorry for my bad English.
Title: Re: pause in a game
Post by: G. on November 15, 2013, 04:33:23 pm
When you press P to exit the pause, these 2 lines are executed:
if (event.type == Event::KeyPressed)
    wait=false;
Then you enter in this if:
if(!wait)
And you immediately enter this if again (because P is still pressed at this moment):
if( Keyboard::isKeyPressed(Keyboard::P))
{
    wait = true;
}
So the game is paused again.

Instead of doing this, you could handle the pause with only the following two lines:
if (event.type == Event::KeyPressed && event.key.code == sf::Keyboard::P)
    wait = !wait;
Each time the P key is pressed, the game pauses or unpauses.
It sets wait to true if it's false (pause the game) and to false if it's true (unpause the game).
Title: Re: pause in a game
Post by: glu4it on November 15, 2013, 04:53:37 pm
Thank you! Now it works :)