Question

I need some help with my SFML/C++ code in Visual C++ 2010 Express Edition. I am trying to get my text (livesLeft) to "You Win!" Before the program sleeps. This is making the player know that he won. But instead, the program goes right to sleep and changes the text right as it is closing, so you only see it change for a few milliseconds. I can't even read it.

    bool play = true;
    bool win = false;
    bool touchFinish = false;

    int lives = 3;

    sf::Font arial;
    if(arial.loadFromFile("Fonts/arial.ttf") == 0)
    {
            return 1;
    }

    sf::Text livesLeft;
    livesLeft.setFont(arial);
    livesLeft.setCharacterSize(30);
    livesLeft.setString("Lives: ");
    livesLeft.setPosition(0, 0);
    livesLeft.setColor(sf::Color::White);

    sf::RectangleShape finish;
    finish.setSize(sf::Vector2f(200, 600));
    finish.setPosition(700, 0);
    finish.setFillColor(sf::Color::Green);

Those are my variables in use and this is my code where I'm trying to change the text:

    if(player.getGlobalBounds().intersects(finish.getGlobalBounds()))
    {
        livesLeft.setString("You Win!");
        touchFinish = true;
    }

    if(touchFinish)
    {
        win = true;
    }

    if(win)
    {
        Sleep(5000);
            play = false;
    }

I also forgot to add in that I do have the rendering at the end:

    window.clear();
    window.draw(livesLeft);
    window.draw(finish);
    window.draw(player);
    window.draw(obs1);
    window.draw(obs2);
    window.draw(obs3);
    window.draw(obs4);
    window.draw(obs5);
    window.draw(obs6);
    window.draw(obs7);
    window.draw(obs8);
    window.draw(obs9);
    window.draw(obs10);
    window.draw(obs11);
    window.draw(obs12);
    window.draw(obs13);
    window.display();
Was it helpful?

Solution

This is most likely due to the fact that you aren't calling the display method for you window. Telling the text to change simply prepares the next framebuffer to display the new text, but because you never tell the window to update its display before sleeping, it never displays the new framebuffer.

Here is a quick example of a simple program using SFML. Notice the window.display() method at the end of the main game loop.

You effectively want to be doing this:

if(win)
{
    window.display();
    Sleep(5000);
    play = false;
}

The reason why you need to update the display before hand again is because Sleep(5000); blocks the thread, essentially meaning that it sits at that call for 5000ms. Also, if you want to keep the previous items on the screen, you'll want to redraw those before window.display(); as well, since these won't be in the next framebuffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top