requestAnimationFrame
is a special timer. Unlike setInterval
which executes the callback repeatedly after a given minimum of milliseconds, requestAnimationFrame
executes variably to achieve smooth framerates.
The problem is how requestAnimationFrame
achieves that. Depending on the situation, it may run faster or slower. What this means is that if your update logic was tied to requestAnimationFrame
directly, a character running at "one step per update" would travel 60 steps in one second when requestAnimationFrame
is running at 60fps, but then would only do 40 when it throttles down to 40fps.
To counteract this sudden speed-up/slow-down of the timer, we use "delta time". Instead of depending on each iteration of requestAnimationFrame
to call an update, you check the time between frames to see if it is the right time to call an update.
So lets say your character should do a step every 100ms. If the game ran at 60fps, 100ms is roughly every 6 frames. This means that for each iteration, your code checks to see if 100ms has elapsed. Around the 6th frame it does, and calls update. Now if the timer ran at 40fps, 100ms is around 4 frames. So same logic, on each iteration it checks if 100ms elapsed. At the 4th frame it does and calls update. With this, you are insured that update is consistently being called regardless of the fluctuations.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…