Turn Every Second
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 4 of 67.
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
EasyThe cube has a Spinner script with a speed of 90. In Update(), make the cube turn around its y axis, speed degrees every second, on any device.
Press Play to watch it, 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon