0

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.

273K
  • 29,503
  • 10
  • 41
  • 64
Shazin
  • 51
  • 1
  • 9
  • I don't see a time period. Speed is change in distance over time. I see nothing that controls how frequently `dy` is applied to the objects position. What I do see is an event loop that will capture 0 to (?) events and discard them until the queue is empty or a close event is read. – Mikel F Mar 30 '23 at 20:06
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Mar 30 '23 at 20:34

1 Answers1

1

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()'.

Topher
  • 451
  • 2
  • 8
  • Can you share a source from where I can learn more – Shazin Mar 30 '23 at 20:08
  • Here is a link to a discussion: https://en.sfml-dev.org/forums/index.php?topic=7068.0 . Here is a link to a video: https://youtu.be/qplKFkcpBMw – Topher Mar 30 '23 at 20:28