Am I using my delta-time incorrectly? (re: simple frame independant movement)

Started by
4 comments, last by arudson 17 years, 2 months ago
I'm using a game loop that has a fixed tick-rate of 10 ms (eg. 100 ticks per second) and so every update my object's position is called using the 10ms number. Let's say one of my object is a ball moving in a straight line at a rate of 50 pixels/second. Would this code be correct: (??) [ pseudo-code ] void BallUpdate(float dt) { x = x + dt y = y + dt } That seems to produce extremely jerky movement and even if I use linear interpolation in-between ticks it still doesn't look very good. Do I need to use time integration for EVERY object that moves based on a fixed tick-rate? (even if the movement is a simple straight-line movement?) If so, can somebody give me an example of how I should modify my above code? Thanks for your help!
Advertisement
What you need to do is multiply your dt by a unit (say 50pixels per second)

so

x = x + 50.0f * dt;
y = y + 50.0f * dt;

What this means is that when 1 second has passed, you will have drawn 50 pixels or put another way, every 10ms, you will draw 0.5 pixels. There are 100 ticks in 1 second so that 100 * 0.5 = 50.

Does this help you at all?

If the number of ticks per second never change during the life of the game then you can use a constant for your timestep.

One more thing: if x and y are int variables, you might get jerky movement. Make sure they're floats.
Q: How many programmers does it take to write a nice piece of software?A: MORE.
Thanks for the replies!

@Adam Hamilton: My tick-rate is a fixed throughout the entire game, so passing any value into BallUpdate is actually pointless (I think). Since I'm doing fixed-rate updates isn't it safe to simply do x = x + dt?

@cobru: My variables are in fact floats. Thanks though!
No. Your fixed timestep simply means that you can do the following

const double dt = 0.01; // We always update every 0.01sconst double maxSpeed = 50; // We never want to go faster than 50 units/secondx += maxSpeed * dt;y += maxSpeed * dt;


Or equivelantly:

x += 0.5;y += 0.5;


So in that way, yes you're right - but you're not doing x = x + dt;, you're doing x = x + (dt * maxSpeed); - dt is the time differential, not the distance travelled in this time. Semantics, I suppose, rather than a syntactic difference.

EDIT: Missed a semicolon
[TheUnbeliever]
Adam Hamilton is correct. Instead of limiting the game's speed to 100hz, and moving your objects by a fixed amount, let your game loop run as fast as it can, and multiply your object's movement (in units per second) by the amount of time that has elapsed since last frame.

This is the only way to do frame independant movement, or animation. The way you had implemented it was entirely dependant on the frames being 100hz.

Just out of curiosity, how are you going about limiting your framerate to 100 fps?

This topic is closed to new replies.

Advertisement