Tutorials

Lerping the Matrix: Implementing Bullet Time in Unity

In this video, I talk about coroutines, and the proper use of Mathf.Lerp

And the code:

[code language=”csharp”]

using UnityEngine;
using System.Collections;

public class BulletTime : MonoBehaviour {
public float minTimeScale = .5f;
public float transitionTime = 1.0f;

bool isBulletTime = false;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Ability")) {
StopCoroutine("ToggleBulletTime"); // make sure we’re not trying to speed up and slow down at the same time
StartCoroutine("ToggleBulletTime");
}
}

IEnumerator ToggleBulletTime () {
isBulletTime = !isBulletTime;

float start = Time.timeScale;
float target = isBulletTime ? minTimeScale : 1.0f;
float lastTick = Time.realtimeSinceStartup; // we need to keep our own deltaTime, since Time.deltaTime is affected by changes to Time.timeScale
float t = 0.0f;

while (t <= 1.0f) {
t += (Time.realtimeSinceStartup – lastTick) * (1.0f / transitionTime);
t += Time.deltaTime * (1.0f / transitionTime);
lastTick = Time.realtimeSinceStartup;

Time.timeScale = Mathf.Lerp (start, target, t); // we need to use a constant start, not our current value, or we run about twice as fast as we’re intending
Time.fixedDeltaTime = 0.02f * Time.timeScale;

yield return null;
}
}

void OnGUI () {
GUI.Box (new Rect(Screen.width – 150, Screen.height – 50, 75, 25), Time.timeScale.ToString ());
}
}

[/code]

Leave a Reply