I've been having some trouble with choppy movement of objects in a game.
If the frame rate isn't capped, the game runs smooth.
If I cap the frame rate at say, 60 fps, the movement is choppy.
An object's movement looks like this...
m_distance += m_speed * GetFrameTime()
Where speed is in pixels per second, and GetFrameTime() returns the time elapsed since the last frame. Note that objects only move in x and y directions.
I'm using SFML, with the functions SetFramerateLimit(60)
and UseVerticalSync(true)
. While trying to address the choppy movement issue, I read an article from an XNA developer about how they update once, render once, and then if there is time left in the game loop < the frame rate (i.开发者_如何学JAVAe. 1/60) then they'll sleep for the rest of that period. I believe this is what SFML does, because I disabled those functions and wrote in that behavior and I got the same symptoms.
Now I'm not saying the above approach is a bad thing. In fact, I like that the application isn't doing needless work (there is a noticeable difference in resource usage when running the application with a set frame limit and without one). However, I really don't know why the movement is choppy. I've read the gafferongames articles but they don't seem to apply here.
Any assistance is appreciated, thanks.
Edit: I've identified the the issue, now just not sure how to solve it.
On the frames where the object "jumps", the m_distance is significantly greater than distances in other frames. On closer inspection, the GetFrameTime() is also significantly greater than previous times between frames (significant is like 2-3 ms difference).
Edit2: I believe I've come up with a solution thanks to http://gafferongames.com/game-physics/fix-your-timestep/ . Set a fixed delta time instead of using GetFrameTime.
The only reason to ever use:
m_distance += m_speed * GetFrameTime();
is if you're trying to get frame-independent movement. In this case, there's no reason to cap your FPS.
When you have a FPS cap such as what SFML implements, I recommend keeping movement constant per frame. That is to say, something like this:
m_distance += m_speed;
精彩评论