Directions
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 25 of 85.
Unity has names for the six directions, each one unit long:
Vector3.right(1, 0, 0) andVector3.left(-1, 0, 0)Vector3.up(0, 1, 0) andVector3.down(0, -1, 0)Vector3.forward(0, 0, 1) andVector3.back(0, 0, -1)
There are also Vector3.zero (0, 0, 0) and Vector3.one (1, 1, 1). Because each direction is one unit long, a direction times a speed is a move of exactly that speed. This snail crawls away from the camera at 0.5 units per second:
public float speed = 0.5f;
void Update()
{
transform.position += Vector3.forward * speed * Time.deltaTime;
}That is the same move as new Vector3(0, 0, speed * Time.deltaTime), but the direction is easier to read and harder to put on the wrong axis. A minus sign flips a direction: -Vector3.forward is Vector3.back. These directions belong to the world, not to the object: Vector3.forward is the world's z even when the snail is turned around. The next lesson moves objects the way they face.
Challenge
EasyDrive the crane's hook with the four arrows, using Unity's named directions.
- In
Update(), write oneifonInput.GetKeyfor each arrow key. - Each adds its direction times
speed * Time.deltaTime:Vector3.right,Vector3.left,Vector3.uporVector3.down, as intransform.position += Vector3.up * speed * Time.deltaTime;.
Press Play and steer: the hook slides, rises and drops. Then Check.
Try it yourself
using UnityEngine;
public class Hook : MonoBehaviour
{
public float speed = 2f;
void Update()
{
// Right/left arrows: slide along x. Up/down arrows: raise and lower.
}
}
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