我有一个简短的问题。我正在学习SFML,并且使用它创建了几个应用程序。有一天,我学习了如何在编码游戏时使用固定的时间步长,如果它能够工作,它会很棒。但。即使我正在制作一个简单的项目,就像从窗口的左侧移动到右侧一样 - 它是滞后的!什么可能是这个问题的原因?这是我的代码:SFML +固定时间步长=滞后?
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Window");
window.setVerticalSyncEnabled(true);
sf::Event event;
sf::Clock clock;
sf::Time accumulator = sf::Time::Zero;
const sf::Time timePerFrame = sf::seconds(1.f/60.f);
sf::RectangleShape square;
square.setSize(sf::Vector2f(32, 32));
square.setOrigin(16, 16);
square.setPosition(400, 300);
square.setFillColor(sf::Color::Red);
int direction = 1;
int speed = 300;
while(window.isOpen())
{
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
window.close();
}
}
while(accumulator >= timePerFrame)
{
if(square.getPosition().x <= 16 || square.getPosition().x >= 784) direction *= (-1);
square.move(sf::Vector2f(speed * direction * timePerFrame.asSeconds(), 0));
accumulator -= timePerFrame;
}
accumulator += clock.restart();
window.clear(sf::Color::Black);
window.draw(square);
window.display();
}
return 0;
}
正如你看到的我是知道的垂直同步,但它不帮助这么多。我的固定时间循环是否错误?任何帮助表示赞赏!
你并不需要自己'SF :: Window'has称为方法来实现这个'setFramerateLimit' – DogeAmazed
谢谢你了迅速的回答。我读过使用这个函数不推荐。 –
忽略我最后的评论,Bosslard的回答启发了我。 –