英文:
Object speed is changing randomly in SFML C++
问题
I have created a little program in SFML C++ where I want an object to move. But my problem is the movement speed is not constant, sometime speed is dropping randomly and the movement is not smooth at all. Can anyone tell me how to stop this behavior also how to make the movement speed smooth.
你好,以下是你提供的代码的翻译:
#include <SFML/Graphics.hpp>
#include <iostream>
// 10^6
int main()
{
float dx = 0.000001;
float dy = 0.03;
int w = 720;
int h = 480;
sf::RenderWindow window(sf::VideoMode(w, h), "Sf Test");
sf::CircleShape r1(20);
r1.setFillColor(sf::Color(250, 0, 0));
sf::Vector2f objPos(0.0, 0.0);
r1.setOrigin(objPos);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
if (r1.getPosition().y > h || r1.getPosition().y < 0)
{
dy *= -1;
}
objPos.y += dy;
r1.setPosition(objPos);
// std::cout << r1.getPosition().y << std::endl;
window.clear();
window.draw(r1);
window.display();
}
}
如果你需要进一步的帮助或解决问题,请随时提出。
英文:
I have a created a little program in SFML C++ where I want an object to move. But my problem is the movement speed is not constant, sometime speed is dropping randomly and the movement is not smooth at all.
Video Link
If you take a closer look the speed is not constant
My Source code
#include <SFML/Graphics.hpp>
#include <iostream>
// 10^6
int main()
{
float dx = 0.000001;
float dy = 0.03;
int w = 720;
int h = 480;
sf::RenderWindow window(sf::VideoMode(w, h), "Sf Test");
sf::CircleShape r1(20);
r1.setFillColor(sf::Color(250, 0, 0));
sf::Vector2f objPos(0.0, 0.0);
r1.setOrigin(objPos);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
if (r1.getPosition().y > h || r1.getPosition().y < 0)
{
dy *= -1;
}
objPos.y += dy;
r1.setPosition(objPos);
// std::cout << r1.getPosition().y << std::endl;
window.clear();
window.draw(r1);
window.display();
}
}
Can anyone tell me how to stop this behavior also how to make the movement speed smooth.
答案1
得分: 1
自从您无法控制系统何时安排/取消安排代码执行,您需要在时间差计算中引入一个时间元素。因此,
objPos.y += (speedY * deltaTime);
您需要在每个循环中计算"deltaTime"。"deltaTime"将是自上次循环发生以来的时间。您可以使用sf::Clock类并依赖"getElapsedTime()"。
英文:
Since you cannot control when the system is going to schedule/unschedule your code for execution, you're going to want to put a time element in your delta calculation.
So,
objPos.y += ( speedY * deltaTime );
You will need to calculate the 'deltaTime' from loop-to-loop. 'deltaTime' will be the time since the last loop happened. You can use the sf::Clock class and work off of 'getElapsedTime()'.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论