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]

Tutorials

Creating a flashlight GameObject in Unity3D

I’ve been playing around with Unity 3D lately, and I put together a short tutorial video about some of what I’ve learned. Enjoy!

Here’s the code used in the video:

[code language=”csharp”]
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Light))]
public class Flashlight : MonoBehaviour {
public GameObject source;
public AudioClip toggleSound;
Light _light;

// Use this for initialization
void Start () {
_light = GetComponent<Light>();
}

// Update is called once per frame
void Update () {
if(Input.GetButtonDown ("Flashlight")) {
_light.enabled = !_light.enabled;
AudioSource.PlayClipAtPoint(toggleSound, transform.position);
}

transform.Rotate(source.transform.rotation.eulerAngles – transform.rotation.eulerAngles);
}
}
[/code]