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
EasyMake the cube turn around its y axis at speed degrees a second.
- In
Update(), calltransform.Rotate(x, y, z). - Put
speed * Time.deltaTimein the middle number, for y, and0for 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground