Menu
CoddyTech

Turn Every Second

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 11 of 85.

transform.Rotate(x, y, z) turns a GameObject by that many degrees around each of its axes. Called in Update(), it turns a little on every frame, so the object keeps turning.

But how many frames is a second? On a fast computer maybe 120, on a phone maybe 30. A plain transform.Rotate(0, 0, 5) would spin four times faster on the fast one. Unity's answer is Time.deltaTime: the seconds that passed since the last frame. Multiply a speed by it and the speed means per second, on every device.

Here a wheel turns around its z axis, 45 degrees every second:

public float speed = 45f;

void Update()
{
    transform.Rotate(0, 0, speed * Time.deltaTime);
}

At 60 frames a second, Time.deltaTime is about 0.0167, so each frame turns 45 * 0.0167, about 0.75 degrees, and 60 of those make 45. At 30 frames a second each frame turns twice as far, and a second still adds up to 45.

challenge icon

Challenge

Easy

Make the cube turn around its y axis at speed degrees a second.

  1. In Update(), call transform.Rotate(x, y, z).
  2. Put speed * Time.deltaTime in the middle number, for y, and 0 for x and z. The wheel above turned on z; this cube turns on y.

Press Play: the cube makes a quarter turn every second. Then Check.

Try it yourself

using UnityEngine;

public class Spinner : MonoBehaviour
{
    public float speed = 90f;

    void Update()
    {
        // Turn the cube around its y axis here
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground