Game Development Reference
In-Depth Information
Exploring deltaTime
Every game relies either directly or indirectly on the concept of time to get its work done. If objects
move or animate or change , then time is necessarily involved since every change must occur at a
specified moment and at a specified speed. For an object to change , it must have been in a different
state at an earlier time; otherwise, no change could be said to have occurred now . Thus, to represent
any kind of change in-game, a concept and measure of time is needed. Measuring time has been
problematic in games, however, historically speaking. Many older games measured time in terms of
frames, but this resulted in performance inconsistency across hardware, because different computers
could sustain different frame rates, and at different times. The result was that no two users on different
computers could be guaranteed the same experience, even if they started playing the same game at
the same time. So nowadays, many games measure time in a hardware-independent way, namely in
terms of seconds. And Unity offers many such time-measuring features through the Time class.
Note For more information on the Time class, see the Unity documentation at
http://docs.unity3d.com/Documentation/ScriptReference/Time.html .
An important member variable of the Time class, which updates on each frame, is deltaTime . In
mathematics and science, as well as video games, the term delta typically means “change in” or
“difference.” Thus, deltaTime refers to time difference or change in time . Specifically, the variable
deltaTime expresses how much time (in seconds) has elapsed since the previous frame. For this
reason, because video games typically display many frames per second, this value will almost
always be a fractional value between 0 and 1, such as 0.03, or 0.5, or 0.111, and so forth. A value of
0.5 would mean that half a second has elapsed since the previous frame, and 1 would mean a whole
second, and 2 would mean 2 seconds, and so on. Normally, larger values such as 1, and 2, and 3
are indicative of lag and problems in your game, because the hardware is clearly unable to sustain
higher frame rates that would necessarily result in lower deltaTime values.
Note For more information on deltaTime, see the Unity documentation at
http://docs.unity3d.com/Documentation/ScriptReference/Time-deltaTime.html .
deltaTime is useful in Unity because it allows us to achieve frame-rate independence. Consider, for
example, a GameObject (such as a spaceship) that should travel in a straight line. Let's say we want
to translate the spaceship on the X axis, over time, to produce movement. One way to implement
this behavior without deltaTime would be as shown in Listing 4-9.
Listing 4-9. Moving an Object Without deltaTime
01 void Update()
02 {
03 //Update spaceship position on x axis each frame
04 spaceship.position += new Vector3(5.0f,0,0);
05 }
 
Search WWH ::




Custom Search