Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท C# Scripting

Time and Frame-Independent Movement

Move objects smoothly in Unity: Time.deltaTime, Translate versus position, MoveTowards, Lerp and SmoothDamp, timers and cooldowns, with runnable C# simulations of each technique.

Moving things is the first thing every game does. This lesson turns the idea from the game loop into working techniques: speed in units per second, moving toward a target without overshooting, smooth easing with Lerp and SmoothDamp, rotating at a constant rate, and timers for cooldowns. Each technique has a runnable plain C# stand-in so you can see the numbers.

The Unity scripts are read-only because the engine does not run here; the math is identical.

Speed times delta time

The basic pattern: a direction (a unit vector), a speed (units per second), and Time.deltaTime:

C#
using UnityEngine;

public class Mover : MonoBehaviour
{
    [SerializeField] float speed = 4f;
    [SerializeField] Vector3 direction = Vector3.right;

    void Update()
    {
        transform.position += direction.normalized * speed * Time.deltaTime;
    }
}

Normalizing the direction matters. Walking diagonally with input (1, 1) has length 1.41, so it would be 41% faster than walking straight unless you normalize it. Vector3.ClampMagnitude(input, 1f) is the gentler alternative for analog sticks, because it keeps partial tilt.

transform.Translate(v) does the same but interprets v in local space by default, so Translate(Vector3.forward * speed * Time.deltaTime) moves forward where the object faces. Pass Space.World to use world axes.

Constant speed in a simulation

This stand-in moves an object for one second at several frame times, with the correct formula. The result is the same distance in every case.

C# Constant speed, any frame time (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The small differences come from the last partial frame; they do not accumulate. Without * dt, the distance would depend on the number of frames.

MoveTowards: arrive exactly

Vector3.MoveTowards(current, target, maxDistanceDelta) moves by at most maxDistanceDelta and never overshoots. It is the right tool for "go to that point at a steady speed" and for patrolling between waypoints:

C#
using UnityEngine;

public class Patrol : MonoBehaviour
{
    [SerializeField] Transform[] waypoints;
    [SerializeField] float speed = 2f;
    int index;

    void Update()
    {
        Vector3 target = waypoints[index].position;
        transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

        if (transform.position == target)                 // reached: exact, because MoveTowards snaps
            index = (index + 1) % waypoints.Length;
    }
}

The equality check works because MoveTowards returns exactly target when it is close enough to arrive. For floats from other calculations, compare distances instead: Vector3.Distance(a, b) < 0.05f.

C# MoveTowards and waypoints (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

It speeds along at 1.5 units per frame, lands exactly on each waypoint, and turns toward the next. No overshoot, no jitter.

Lerp: blending, and its famous misuse

Mathf.Lerp(a, b, t) returns a point between a and b: a + (b - a) * t, with t clamped to 0..1. Used properly, t goes from 0 to 1 over a duration:

C#
// read-only Unity script: move from A to B in 2 seconds, with a fixed start
float elapsed;
Vector3 start, end;
void Begin() { start = transform.position; end = start + Vector3.up * 3; elapsed = 0; }

void Update()
{
    elapsed += Time.deltaTime;
    float t = Mathf.Clamp01(elapsed / 2f);
    transform.position = Vector3.Lerp(start, end, t);
}

The widely seen shortcut is position = Vector3.Lerp(position, target, 0.1f); every frame. It makes an exponential ease-out: each frame covers 10% of the remaining distance, so it starts fast and slows near the target, and it depends on frame rate (more frames means faster approach). It is okay for quick prototypes and cameras, but remember its behavior. A frame-rate-independent version is 1 - Mathf.Exp(-rate * Time.deltaTime) as the blend factor.

Vector3.SmoothDamp(current, target, ref velocity, smoothTime) gives a smooth, critically damped follow with its own velocity, ideal for cameras:

C#
Vector3 velocity;
void LateUpdate()
{
    transform.position = Vector3.SmoothDamp(transform.position, target.position + offset, ref velocity, 0.25f);
}

Comparing Lerp styles

This stand-in compares the Lerp usages and the exponential, frame-rate independent form, at 30 FPS and 120 FPS over one second.

C# Lerp styles at 30 and 120 FPS (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The fixed-fraction Lerp (2% per frame) reaches about 4.5 at 30 FPS but 9.1 at 120 FPS: the same code, very different behavior. The exponential and the timed versions agree across frame rates.

Rotating

Rotate at a constant rate in degrees per second:

C#
transform.Rotate(0f, 90f * Time.deltaTime, 0f);                     // spin around Y
transform.Rotate(Vector3.up, 90f * Time.deltaTime, Space.World);   // around the world Y axis

// turn toward a target at a limited turn speed
Vector3 toTarget = (target.position - transform.position).normalized;
Quaternion look = Quaternion.LookRotation(toTarget);
transform.rotation = Quaternion.RotateTowards(transform.rotation, look, 180f * Time.deltaTime);

Quaternion.RotateTowards is the angle version of MoveTowards: it turns at most the given number of degrees per frame. Quaternion.Slerp is the spherical equivalent of Lerp.

Timers and cooldowns

Games are full of waiting: a weapon cooldown, a respawn delay, a power-up lasting 5 seconds. Two patterns:

C#
// 1. Count down with deltaTime
float cooldown;
void Update()
{
    cooldown -= Time.deltaTime;
    if (Input.GetKeyDown(KeyCode.Space) && cooldown <= 0f)
    {
        Fire();
        cooldown = 0.5f;
    }
}

// 2. Compare with Time.time (time since start)
float nextFireTime;
void TryFire()
{
    if (Time.time >= nextFireTime)
    {
        Fire();
        nextFireTime = Time.time + 0.5f;
    }
}

For waits inside a sequence ("wait 2 seconds, then open the door"), a coroutine reads better; see Instantiate, Destroy and Coroutines.

C# A fire-rate cooldown (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Moving with physics instead

Everything above changes transform directly, which is fine for objects without a Rigidbody (cameras, UI, kinematic scenery). For physical objects use the Rigidbody API in FixedUpdate (rb.MovePosition, rb.linearVelocity, AddForce); see Rigidbody and Colliders. Moving a Rigidbody through its transform makes it teleport through walls and jitter.

Common mistakes

  • Forgetting Time.deltaTime, or multiplying twice by it.
  • Moving at Update rate for physics objects.
  • Using Lerp(a, b, 0.1f) and expecting a constant speed.
  • Comparing positions with == after Lerp (it never quite arrives); use MoveTowards or a distance threshold.
  • Using Time.time for timers while Time.timeScale is 0 and the timer must still run: use Time.unscaledTime.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A character moves 0.2 units per Update call. What is wrong?

    Per-frame movement is faster at high frame rates. Use speed * Time.deltaTime.
  2. 2. Which function never overshoots its target?

    MoveTowards limits the step to the remaining distance.
  3. 3. Why normalize an input direction before multiplying by speed?

    The vector (1,1) is longer than (1,0), so a diagonal would be about 41% faster without normalizing.
  4. 4. Vector3.Lerp(position, target, 0.1f) called every frame gives:

    Each frame covers 10% of the remaining distance, so it slows near the target and runs faster at higher frame rates.

Summary

  • Speed in units per second multiplied by Time.deltaTime gives distance per frame.
  • Normalize or clamp input directions.
  • MoveTowards and RotateTowards give constant-speed arrival; Lerp with a growing t gives timed blending; SmoothDamp gives smooth following.
  • Cooldowns use a countdown or Time.time comparison.
  • Use Rigidbody methods in FixedUpdate for physical movement.

Next: Finding and Referencing Components