setFramerateLimit() 函数在 sfml 中不起作用

setFramerateLimit() function not working in sfml

我正在尝试学习 SFML,我想限制帧速率。这是我的代码:-

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

int main()
{
    sf::Window win (sf::VideoMode(200,200),"SDSDefgwre");
    sf::Clock clock;
    win.setFramerateLimit(30);

    sf::Time t;
    while(win.isOpen())
    {
        sf::Event e;
        clock.restart().asSeconds();
        while(win.pollEvent(e))
        {
            if(e.type == sf::Event::Closed)
                win.close();
        }    
        t = clock.getElapsedTime();    
        std::cout << 1.f/t.asSeconds() <<'\n';    
    }   
    return 0;
}

我在 运行 这段代码中得到 200000 FPS。这意味着

    win.setFramerateLimit(60);

无效。请告诉我哪里出错了?

来自 setFrameLimit 的文档:

If a limit is set, the window will use a small delay after each call to display() to ensure that the current frame lasted long enough to match the framerate limit.

你不渲染任何东西,你从来没有真正交换绘图缓冲区(这是对 win.display() 的调用会做的)。

问题是你没有打电话

win.display()

因为window在显示函数中等待帧

您的代码应如下所示

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

int main()
{
    sf::Window win(sf::VideoMode(200, 200), "SDSDefgwre");
    sf::Clock clock;
    win.setFramerateLimit(30);

sf::Time t;
while (win.isOpen())
{
    sf::Event e;
    clock.restart().asSeconds();
    while (win.pollEvent(e))
    {
        if (e.type == sf::Event::Closed)
            win.close();
    }
    win.display();
    t = clock.getElapsedTime();
    std::cout << 1.0 / t.asSeconds() << '\n';
}
return 0;
}