Slow Motion
Part of the Building Real Games section of Coddy's Unity journey. Lesson 34 of 56.
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
MediumA comet crosses the sky, and Space launches it from the left (Launcher.cs, ready). On its way it flies through the SlowZone, a trigger box, and that part of its flight should play in slow motion. Write SlowZone.cs:
- When something enters the zone, game time runs at
slowScale(0.4 in the Inspector), and the physics step shrinks by the same factor from 0.02, so the comet still moves smoothly. - When it leaves the zone, time runs at normal speed again, with the physics step back at 0.02.
Press Play, press Space and watch the comet pass through, then Check.
Try it yourself
using UnityEngine;
public class SlowZone : MonoBehaviour
{
public float slowScale = 0.4f;
// Slow motion while something is inside the zone
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap