Local and World Space
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 26 of 85.
An object has its own directions as well as the world's. transform.forward is where the object's nose points (the blue arrow in Unity's Scene view), given as a world vector one unit long; transform.right and transform.up are its own right and up. Turn the object and they turn with it. This paper plane is turned 90 degrees around y in the scene, so it flies along the world's x, the way it points:
public float speed = 4f;
void Update()
{
transform.position += transform.forward * speed * Time.deltaTime;
}transform.Translate(Vector3.forward * speed * Time.deltaTime) does the same thing, because Translate reads its vector in the object's own space: there, Vector3.forward means the object's forward. Pass Space.World as a second argument and it uses the world's axes instead, so transform.Translate(Vector3.forward * speed * Time.deltaTime, Space.World) moves along the world's z whichever way the plane points.
transform.Rotate also turns around the object's own axes. Seen from above, a positive angle around y turns an upright object to its right and a negative one to its left, and its transform.forward turns with it.
Challenge
EasyGive the tank tank controls: turn on the spot, drive the way it faces.
- In
Update(), while the right arrow is held,transform.Rotate(0, turn * Time.deltaTime, 0);, and with-turnfor the left arrow. - While the up arrow is held,
transform.Translate(Vector3.forward * speed * Time.deltaTime);.
Press Play, turn and drive: the tank goes where its nose points. Then Check.
Try it yourself
using UnityEngine;
public class Tank : MonoBehaviour
{
public float speed = 3f;
public float turn = 90f;
void Update()
{
// Right/left arrows: turn around y. Up arrow: drive the way the tank faces.
}
}
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