Menu
CoddyTech

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) and Vector3.left (-1, 0, 0)
  • Vector3.up (0, 1, 0) and Vector3.down (0, -1, 0)
  • Vector3.forward (0, 0, 1) and Vector3.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 icon

Challenge

Easy

Drive the crane's hook with the four arrows, using Unity's named directions.

  1. In Update(), write one if on Input.GetKey for each arrow key.
  2. Each adds its direction times speed * Time.deltaTime: Vector3.right, Vector3.left, Vector3.up or Vector3.down, as in transform.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

Practice on your own: Unity playground