Menu
CoddyTech

Slow Motion

Part of the Building Real Games section of Coddy's Unity journey. Lesson 35 of 60.

A Time.timeScale between 0 and 1 is slow motion. At 0.25, Time.deltaTime is a quarter of the real frame time, so a car moved by speed * Time.deltaTime covers a quarter of its distance each real second, Rigidbodies fly and fall at a quarter of their speed, and WaitForSeconds(1f) lasts 4 real seconds. Above 1 the game runs fast: 2 is double speed.

Physics needs one more line. Each physics step still moves the game on by Time.fixedDeltaTime, 0.02 seconds of game time, and at 0.25 those take 0.08 real seconds: FixedUpdate() runs only 12.5 times a real second, so bodies move on one frame in five and stutter. Shrink the step by the same factor, and put both values back afterwards, since Unity never resets fixedDeltaTime on its own. This script slows the game while Space is held:

float normalStep;

void Awake()
{
    normalStep = Time.fixedDeltaTime;   // 0.02 in a new project
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Time.timeScale = 0.25f;
        Time.fixedDeltaTime = normalStep * Time.timeScale;
    }
    if (Input.GetKeyUp(KeyCode.Space))
    {
        Time.timeScale = 1f;
        Time.fixedDeltaTime = normalStep;
    }
}

With the smaller step, physics still steps 50 times a real second and each step covers a quarter of the game time, so the slow motion stays smooth. The step is in game seconds, so code in FixedUpdate() that uses Time.deltaTime keeps working unchanged.

challenge icon

Challenge

Medium

Play the comet's flight through the SlowZone in slow motion.

  1. In SlowZone.cs, write void OnTriggerEnter(Collider other): set Time.timeScale to slowScale and Time.fixedDeltaTime to 0.02f * slowScale.
  2. Write void OnTriggerExit(Collider other): set them back to 1f and 0.02f.

Press Play and Space: the comet glides through the zone at 0.4 speed. Then Check.

Try it yourself

using UnityEngine;

public class SlowZone : MonoBehaviour
{
    public float slowScale = 0.4f;

    // Slow motion while something is inside the zone
}

All lessons in Building Real Games

Practice on your own: Unity playground