Game Development Reference
In-Depth Information
39 //Distance travelled so far
40 float DistanceTravelled = 0;
41
42 //Move
43 while(DistanceTravelled < TravelDistance)
44 {
45 //Get new position based on speed and direction
46 Vector3 DistToTravel = MoveDir * Speed * Time.deltaTime;
47
48 //Update position
49 ThisTransform.position += DistToTravel;
50
51 //Update distance travelled so far
52 DistanceTravelled += DistToTravel.magnitude;
53
54 //Wait until next update
55 yield return null;
56 }
57 }
58 //--------------------------------------------------------------
59 }
Lines 16 and 20. These should be familiar to us. In line 16 we declare a private
ThisTransform object to cache the GameObject transform, ready to use either
during coroutines or Update functions. In line 20, Start is declared as a coroutine
rather than a regular function since we'll be waiting on Travel to complete in line
32. The Travel coroutine is used to move the power-up up and down.
Lines 07 and 29. Line 07 declares a public Vector3 MoveDir , which should be
set for each GameObject in the Object Inspector. This vector represents the
starting direction in which an object should move for the specified distance
TravelDistance (declared in line 13) and at the specified Speed (declared in line
10). This vector should be in a normalized form. By normalized here, I mean
MoveDir is expected to use the values of 0 or 1 to indicate direction. Thus, if an
object should move upward on the Y axis, the MoveDir vector would be (0,1,0) .
Movement on X would be (1,0,0), and on Z would be (0,0,1).
Lines 26-32. Power-up objects should move up and down endlessly in a loop .
This is where that high-level functionality happens. If MoveDir begins with a
value of (0,1,0), then it's value is inverted at line 29 to (0,-1,0), and the Travel
coroutine is called, to move the object downward at a specified speed and for a
specified distance. On reaching the destination, the Travel coroutine completes,
and MoveDir is inverted again. So (0,-1,0) becomes (0,1,0), and then the object
moves up, and so on. Thus, through repeated inversion, we achieve PingPong.
Lines 37-55. The Travel coroutine is responsible moving the power-up object
from its current world space position, in the direction of MoveDir , at a specified
speed , and until the total distance traveled exceeds TravelDistance . This is
achieved especially with line 46, which calculates the amount to move in the
direction MoveDir for the current frame . To calculate this, a Unity API variable
Time.deltaTime is used. The next section discusses deltaTime further.
 
Search WWH ::




Custom Search