Game Development Reference
In-Depth Information
This code increments the X position of the Player spaceship on each frame by five units. Over time,
this will cause the spaceship to move. The problem, however, is that the speed of the spaceship
entirely depends on the frequency with which Update is called. The more frequently Update is called,
the faster the spaceship will move. Of course, we know in advance that Update is called on each and
every frame, but frame rates differ across computers and even on the same computer at different
times. For this reason, the code in Listing 4-9 will result in a spaceship that travels at different
speeds on different computers, and even at different times on the same computer. This might not
be a problem for us, if we don't care about spaceship speed in any way. But typically, we do care
because we want to have some degree of control and understanding about the kind of experience
gamers will have when they play our game. Now, we can solve this problem using deltaTime. Let's
see how. Consider the following code in Listing 4-10, which improves on Listing 4-9.
Listing 4-10. Moving an Object with deltaTime
01 using UnityEngine;
02 using System.Collections;
03 //--------------------------------------------------------------
04 public class Mover : MonoBehaviour
05 {
06 //Speed to move - units per second (5 units per second)
07 public float Speed = 5.0f;
08
09 //Cached Transform
10 private Transform ThisTransform = null;
11
12 //--------------------------------------------------------------
13 //Move spaceship
14 void Update()
15 {
16 //Update position
17 ThisTransform.position += new Vector3( Speed * Time.deltaTime , 0, 0);
18 }
19 //--------------------------------------------------------------
20 }
In Listing 4-10, the speed of the spaceship is defined in a ratio of units to seconds, namely world
units per second . Further, we know that deltaTime expresses time as a fraction, based on how much
time has elapsed since the previous frame. And lastly, we know that calculating the distance traveled
for an object can be expressed using this formula: Distance = Speed × Time . Therefore, Speed ×
deltaTime results in the amount of world units the spaceship should travel. This allows you to move
the spaceship not only a constant speed during gameplay, but a constant speed between different
computers. The lesson here, then, is for moving objects use deltaTime !
Completing Power-Up Bobbing
We've now seen deltaTime in action, for creating a sample case of a spaceship moving forward
along the X axis over time at a consistent speed. We've also seen in Listing 4-7 how deltaTime
can be applied to the PingPongDistance class to create motion for power-ups. This means we can
now move further with the Cash Power-Up. So, back in the Unity Editor, just drag and drop the
 
Search WWH ::




Custom Search