How It Works

If you’ve ever used Unity’s coroutines before then the following block might look familiar:

public Transform Item;
public Vector3 TargetPosition;

void Start()
{
     StartCoroutine(MoveItem(Item, TargetPosition, 5f));
}
 
IEnumerator MoveItem(Transform item, Vector3 target, float timeframe)
{
     float startTime = Time.time;
     Vector3 startPos = item.position;
 
     while(startTime + timeframe <= Time.time)
     {
          item.position = Vector3.Lerp(startPos, target, (startTime - Time.time) / timeframe);
 
          yield return null;
     }
}

 
The code above runs a coroutine that will update the position of the item every frame so that it gets closer and closer to the position of targetuntil, after 5 seconds, it finally reaches target. The key processing happens inside the while loop where start.position gets set to the result of Vector3.Lerp. It’s the line with the Vector3.Lerp command that really does all the interesting work, but in order to accomplish that one simple movement we have to surround it with approximately 15 lines of boilerplate code!

Movement over Time does the same basic thing: It also runs a loop which calculates a new position every frame to create a smooth transition between the starting position and the ending position. We’ve improved the basic loop above in several ways that you probably never considered (like making it work even when time is running backwards) and we’ve optimized each and every line.

With Movement over Time the syntax is a little different: Instead of writing out a function full of boilerplate code, you just define the key actions which will be executed at the key points in the loop. These actions aren’t variables, they are typically anonymous functions which do one simple thing and do it well.

Effect<Controller, float> goUp = new Effect<Controller, float>
{
     Duration = 5f,
     RetrieveEnd = (me) => me.TargetPosition,
     OnUpdate = (me, value) => me.Item.position = value
};
 
Sequence<Controller, float> rise = new Sequence<Controller, float>
{
     Reference = this,
     RetrieveSequenceStart = me => me.Item.position
};
 
rise.Add(goUp);
 
Movement.Run(rise);

 
The above code is an example of how you start a sequence in Movement over Time.

  1. Define an effect, which holds a few key methods and the duration.
  2. Define a sequence which holds the rest of the methods we need in order to perform this particular transition.
  3. Add the effect to the sequence.
  4. Start the sequence running.