Menu
CoddyTech

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 icon

Challenge

Easy

Give the tank tank controls: turn on the spot, drive the way it faces.

  1. In Update(), while the right arrow is held, transform.Rotate(0, turn * Time.deltaTime, 0);, and with -turn for the left arrow.
  2. 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

Practice on your own: Unity playground