Menu
CoddyTech

Look At Things

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

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

The rover already drives with the arrows along the world's x and z axes. Make it face the way it drives: while it moves, its front (its forward axis) points in the direction of travel, diagonals included. With no key held, it stands still and keeps facing the way it last drove.

Press Play, drive around, 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
    }
}
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