Menu
CoddyTech

Look At Things

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 34 of 85.

transform.LookAt(point) turns an object so that its forward axis, the blue z arrow, points at a position in the world. It turns the object and does not move it. This searchlight sits on a tower at (0, 6, 0) and aims at the gate at (4, 0, 10):

void Start()
{
    transform.LookAt(new Vector3(4, 0, 10));
}

The gate is lower than the light, so the searchlight tilts down as well as turning: LookAt aims straight at the point, up or down included. Afterwards transform.forward points from the light toward the gate.

Called in Start(), LookAt aims once. Called in Update(), it aims again on every frame, so the object keeps facing the point while the object or the point moves. Its argument is always a position: LookAt(Vector3.forward) aims at the world point (0, 0, 1), a spot next to the world's center, wherever the object happens to be.

challenge icon

Challenge

Medium

Make the rover face the way it drives.

  1. Below the comment in Update(), write if (move != Vector3.zero), so a standing rover keeps its facing.
  2. Inside it, call transform.LookAt(transform.position + move);.

Press Play and drive: the rover turns its front toward where it goes. Then Check.

Try it yourself

using UnityEngine;

public class Rover : MonoBehaviour
{
    public float speed = 3f;

    void Update()
    {
        Vector3 move = Vector3.zero;
        if (Input.GetKey(KeyCode.RightArrow)) move += Vector3.right;
        if (Input.GetKey(KeyCode.LeftArrow)) move += Vector3.left;
        if (Input.GetKey(KeyCode.UpArrow)) move += Vector3.forward;
        if (Input.GetKey(KeyCode.DownArrow)) move += Vector3.back;
        move = move.normalized;
        transform.position += move * speed * Time.deltaTime;
        // Turn the rover to face the way it is driving
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground