SFML community forums

Help => General => Topic started by: ineed.help on July 23, 2014, 05:13:10 pm

Title: Problem with waiting
Post by: ineed.help on July 23, 2014, 05:13:10 pm
Hello.

Currently, I am working on a program which prints a character and then waits for 100 milliseconds, after which it prints a second character.

However, I also have a... well, let's call it a "box". When the mouse clicks on this box, it changes color.

I have figured most of this out. However, I have a problem due to the wait time. This is, in mostly psuedo-code, what's giving me trouble.

sf::RenderWindow window;

while (!shouldStop)
{
        window.clear(sf::Color::White);
        window.draw(boxSprite_NotSelected);

        // print characters, etc.

        if (boxRectangle.Contains(GetMousePosition())
        {
                if (IsLeftMouseButtonPressedInRectangle())
                { shouldStop = true; window.draw(boxSprite_Selected); }
        }

        window.display();
        sf::sleep(sf::milliseconds(100));
}
 

During the sleep time of 0.1 seconds, if I click on the box, it, obviously, doesn't register. What I want to know is how to fix this. Should I not use sf::sleep? What do I do?
Title: Re: Problem with waiting
Post by: Stauricus on July 23, 2014, 05:47:06 pm
of course, if the loop is sleeping, it will not detect any inputs.
look for sf::Time and sf::Clock to do this. every loop you check if the clock time is 100miliseconds or more, and if it is, you reset the clock and change your character :)
Title: Re: Problem with waiting
Post by: ineed.help on July 23, 2014, 05:51:21 pm
I want it to change characters after pretty much EXACTLY 0.1 seconds, is this possible this way?
Title: Re: Problem with waiting
Post by: Stauricus on July 23, 2014, 05:57:36 pm
yes, it is really precise. i can't test it now, but it would be something like this:

sf::RenderWindow window;
sf::Clock clock;
while (!shouldStop)
{
        window.clear(sf::Color::White);
        window.draw(boxSprite_NotSelected);

        if (clock.getElapsedTime() >= sf::milliseconds(100){
            // print characters, etc.
            clock.restart();
        }

        if (boxRectangle.Contains(GetMousePosition())
        {
                if (IsLeftMouseButtonPressedInRectangle())
                { shouldStop = true; window.draw(boxSprite_Selected); }
        }

        window.display();
        //sf::sleep(sf::milliseconds(100));
}
 
Title: Re: Problem with waiting
Post by: ineed.help on July 23, 2014, 05:59:44 pm
Yes, I tried it out, and it seems to work perfectly! Thanks!

(On a side note, I can't believe I never realized how to do this myself...  :-[)