SFML community forums

Help => General => Topic started by: SFMLNewbie on November 10, 2014, 02:03:21 am

Title: Smooth Movement
Post by: SFMLNewbie on November 10, 2014, 02:03:21 am
I'm trying to make a sprite move at a constant and smooth rate by using a constant speed multiplied by the time elapsed from last frame.

sf::Clock clk;
clk.restart();
    while (window.isOpen())
    {
               
        sf::Event event;
            float dt;
        while (window.pollEvent(event) || true)
        {
                        dt = clk.restart().asSeconds();

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
                        {
                                sprite.move(playerSpeed*dt,0);
                        }

                        window.clear();
                        window.draw(sprite);
                        window.display();
        }
    }
 

This does not result in smooth movement. Occasionally the dt value will spike from 0.0003 to .0010 or something like that, causing the sprite to jump forward even though the difference in time is negligible.

Is there some way to account for these small variations or am I approaching smooth movement wrong all together?

Thanks.
Title: Re: Smooth Movement
Post by: Gobbles on November 10, 2014, 02:40:24 am
As your game loop grows, the dt is going to get bigger and bigger, fluctuating a lot. You need to Fix your time step  http://gafferongames.com/game-physics/fix-your-timestep/
Title: Re: Smooth Movement
Post by: Nexus on November 10, 2014, 02:41:26 am
See http://stackoverflow.com/q/18306101 for example.

For game logic, I recommend using a fixed time step -- it makes things simpler and deterministic.
Fix your timestep (http://gafferongames.com/game-physics/fix-your-timestep/) is also an interesting article in this context.