SFML 在屏幕上移动矩形时滞后/小卡顿



每当我在屏幕上移动矩形时,它似乎有时会卡顿。我尝试重新安装 SFML,但它没有奏效。 这是代码:

#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "This is the title");
window.setFramerateLimit(60);
sf::RectangleShape rect(sf::Vector2f(20, 20));
rect.setFillColor(sf::Color::Green);
rect.setPosition(sf::Vector2f(50, 50));
while (window.isOpen())
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
rect.move(0, -5);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
rect.move(0, 5);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
rect.move(-5, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
rect.move(5, 0);
}

sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{

window.close();

}
}
window.clear();
window.draw(rect);
window.display();
}
return 0;
}

这些是我的笔记本电脑规格:

核心 6y30 英特尔 HD 515 8Gb 内存 视窗 10

如果有人知道问题是什么,请帮助我。 谢谢 亨利

根据Jesper的评论,在制作图形时必须考虑您的时间步长。时间步长是不同帧之间的时间。有几种方法可以解决这个问题。Jesper引用的这个页面(修复你的时间步(完美地总结了它们。这是一种参考。

我做了一个快速的代码调整来给你一些指导。代码适用于 Linux。

#include <SFML/Graphics.hpp>
#include <iostream>
int main(){
sf::RenderWindow window(sf::VideoMode(800, 600), "This is the title");
window.setFramerateLimit(60);
sf::RectangleShape rect(sf::Vector2f(20, 20));
rect.setFillColor(sf::Color::Green);
rect.setPosition(sf::Vector2f(50, 50));
// Timing
sf::Clock clock;
while (window.isOpen()){
// Update the delta time to measure movement accurately
sf::Time dt = clock.restart();
// Convert to seconds to do the maths
float dtAsSeconds = dt.asSeconds();
// For debuging, print the time to the terminal
// It illustrates the differences
std::cout << "Time step: " << dtAsSeconds << 'n';
// Calculate movement per dt
// Since the dt is a very small number, 
// you have to multiply it with a large number to see faster movement
float movement = 250.0f * dtAsSeconds;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
rect.move(0, -movement);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
rect.move(0, movement);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
rect.move(-movement, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
rect.move(movement, 0);
}

sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed){
window.close();
}
}
window.clear();
window.draw(rect);
window.display();
}
return 0;
}

最新更新