Menu
CoddyTech

Directions

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 18 of 67.

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 arrows at speed units per second: the right and left arrows slide it right and left along x, the up arrow raises it and the down arrow lowers it. Use Unity's named directions. With no key held, it stays where it is.

Press Play and steer the hook, then press 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.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics