Home > Software design >  C SFML Text flickers when drawn
C SFML Text flickers when drawn

Time:12-24

So, I have an SFML RenderWindow, and when it closes, it'll display a confirmation message. I've run into this same problem a lot of times: the confirmation message (an sf::Text) is drawn when the Event::Closed is called, but it only stays when the event is called; I think till the click on the close button is registered (calling the close event); disappears in a flash (does that have something to do with the speed of C ?). How can I solve this? The text should be displayed after it's drawn, and shouldn't disappear, after calling the close event.

Here is the code (in main.cpp):

while (app.isOpen())
    {

        // Process events
        sf::Event event;
        while (app.pollEvent(event))
        {

            // Close window : exit
            if (event.type == sf::Event::Closed)
            {
                app.clear();
                Text close("Are you sure you want to close this?", Arial);
                app.draw(close);
                close.setCharacterSize(40);
                close.setPosition(300, 300);
                app.display();
            }

        }

        // Clear screen
        app.clear();

        // Draw the sprite
        app.draw(sprite);
        app.draw(text);
        text.setPosition(500, 500);

        // Update the window
        app.display();
    }

The workaround gives me an error:
I made a function to do the work, but it gives me this error:

error: use of deleted function 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)'.

Here is the code. What am I doing wrong?

Thanks in advance!

CodePudding user response:

Keep an explicit variable with the state of the game, and change your game code based on that:

enum class GameState { Playing, Closing };
GameState phase = GameState::Playing;
while (app.isOpen()) {

    // Process events
    sf::Event event;
    while (app.pollEvent(event)) {

        // Close window : exit
        if (event.type == sf::Event::Closed) {
            phase = GameState::Closing;
        }

    }

    // Clear screen
    app.clear();

    if (phase == GameState::Closing) {
        Text close("Are you sure you want to close this?", Arial);
        close.setCharacterSize(40);
        close.setPosition(300, 300);
        app.draw(close);
    } else if (phase == GameState::Playing) {
        app.draw(sprite);
        app.draw(text);
        text.setPosition(500, 500);
    }

    // Update the window
    app.display();
}
  • Related