window.display() 单独在最后显示的和当前显示的缓冲区之间切换

window.display() alone toggles between the last and current buffer displayed

我制作了这段显示计时器并在您按空格键时暂停的代码:

#include <SFML/Graphics.hpp>
#include <iostream>

using namespace sf;
using namespace std;
void events();

bool pause, exitPause;
char key;
double timeFrame, timeTot = 0;
Clock timer;
Text text;
Font font;

RenderWindow window(VideoMode(800, 600), "Window", Style::Close);

int main()
{
    font.loadFromFile("C:/Windows/Fonts/arial.ttf");
    text.setFont(font);
    text.setCharacterSize(15);
    window.setFramerateLimit(120);
    while (window.isOpen())
    {
        for (Event event; window.pollEvent(event);) {
            if (event.type == Event::Closed)
                window.close();
            if (event.type == Event::TextEntered) {
                key = std::tolower(static_cast<char>(event.text.unicode));
                if (key == ' ') {
                    pause = !pause;
                    if (!pause) {
                        timer.restart();
                    }
                }
            }
        }
        if (!pause) {
            timeFrame = timer.restart().asSeconds();
            timeTot += timeFrame;
            text.setString(to_string(timeTot));
            window.clear();
            window.draw(text);
        }
        window.display();
    }
}

如果你测试,你会看到一些奇怪的东西。按空格键暂停时,window.display 在最后显示的数字和当前显示的数字之间交替。

但是如果我把window.clearwindow.drawwindow.display放在一起,问题就不会发生。

        if (!pause) {
            timeFrame = timer.restart().asSeconds();
            timeTot += timeFrame;
            text.setString(to_string(timeTot));
        }
        window.clear();
        window.draw(text);
        window.display();

我认为 windows.display 单独使用只会显示最后一个缓冲区。 有什么问题?

暂停的那一刻,您就停止更新绘图缓冲区。 SFML always 双缓冲,在每次迭代中你 always 需要解析输入,更新任何需要更新的内容,重绘 "hidden"帧,然后翻转缓冲区。这基本上是一个 "Game Loop" 模式。

在您的代码中,您总是解析输入、更新计时器并基于此暂停状态,并且您总是翻转缓冲区(使用 window.display())。但是,如果状态未暂停,您只能重绘 "hidden" 帧缓冲区。

因此,您看到了预期的输出,并且找到了正确的解决方案。

顺便说一句,您的代码中确实存在几个样式问题,包括未初始化的变量,这在 C++ 中总是很危险。