How can we use delta time?
The problem
Let’s say we’re at 60 FPS and we move our sphere by 10 cm every frame to reach a point that’s 1000 cm on the X axis.
// The sphere takes 1.65 seconds to travel 1000 cm
10 frame/s * 60 frames/s = 600 cm/s
What happens if our frame-rate drops to 30 or 15 FPS?
// The sphere takes 3.3 seconds to travel 1000 cm
10 frame/s * 30 frames/s = 300 cm/s
// The sphere takes 6.6 seconds to travel 1000 cm
10 frame/s * 15 frames/s = 150 cm/s
Because we have less frames in a second to work with, the sphere’s position gets updated less frequently, and we cover less distance per second, so it takes longer to reach it’s destination. That’s why the sphere feels like it moves slower in lower frame-rates.
This is a problem considering we can’t always assure the game will be running at 60FPS across every device.
The solution
Instead of thinking “How much should the sphere move PER FRAME?”, we should be asking “How much to move it by PER SECOND?”
If we want our sphere to move by 250 cm/s, we can multiply it by delta time, and it’s gonna give us the value by which we offset the sphere each frame.
Distance/s * DeltaTime = Distance/frame
// 60 FPS
250 cm/s * 0.016666 = 4.167 cm/frame
// 30 FPS
250 cm/s * 0.033333 = 8.333 cm/frame
// 15 FPS
250 cm/s * 0.066666 = 16.667 cm/frame
Now all the spheres reach their destination after 4 seconds of movement.
This is basically saying “if our game updates once every 0.016666 seconds (60 times in 1 second), how much do we have to move our sphere per update, so it covers 250 cm by the time that 1 second passes.
This is another way of thinking about it
250 cm/s / 60 FPS = 4.167 cm/frame
but we don’t calculate it like this because 60 FPS is more of a by-product of the delta time. 60 FPS is more of an intuitive number for the user to perceive how “smooth” the gameplay is (instead of saying 0.01666).
But really, delta time is the information given to us by the engine, and that’s what we use to calculate the FPS, not the other way around.
When we have 15 FPS, we offset the sphere by 16.667 cm/s, because since we have less frames to work with, the distance traveled per frame needs to be higher, to compensate. This results in a “choppy” look, but at least it’s consistent on a per-second basis and the spheres reach their destination at the same time.
Remember, we’re still updating the sphere’s position per frame, but that value is determined based on how much we want it to move per second. That’s what we want to think about. The per-frame value gets determined at runtime through the formula, and it’s always changing at least slightly, because the delta-time is changing all the time (unless capped). This is because the scene keeps changing – maybe we change the camera angle, or we start moving, or the lighting changes slightly – these are things, albeit very small, will add some variance to how long things take to render.