Game Development Reference
In-Depth Information
Note For more information on coroutines, consult the Unity documentation at
http://docs.unity3d.com/Documentation/Manual/Coroutines.htm l .
Power-Up Motion with Coroutines and deltaTime
Listing 4-8 provides the complete class for PingPongDistance . And this class is also included in
the topic companion files for this chapter at Chapter2/AssetsToImport . Rather than go into lengthy
descriptions here, let's first see the code, and then I'll offer comments.
Listing 4-8. PingPongDistance - Complete Class
01 using UnityEngine;
02 using System.Collections;
03 //--------------------------------------------------------------
04 public class PingPongDistance : MonoBehaviour
05 {
06 //Direction to move
07 public Vector3 MoveDir = Vector3.zero;
08
09 //Speed to move - units per second
10 public float Speed = 0.0f;
11
12 //Distance to travel in world units (before inverting direction and turning back)
13 public float TravelDistance = 0.0f;
14
15 //Cached Transform
16 private Transform ThisTransform = null;
17
18 //--------------------------------------------------------------
19 // Use this for initialization
20 IEnumerator Start ()
21 {
22 //Get cached transform
23 ThisTransform = transform;
24
25 //Loop forever
26 while(true)
27 {
28 //Invert direction
29 MoveDir = MoveDir * -1;
30
31 //Start movement
32 yield return StartCoroutine(Travel());
33 }
34 }
35 //--------------------------------------------------------------
36 //Travel full distance in direction, from current position
37 IEnumerator Travel()
38 {
 
Search WWH ::




Custom Search