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
MediumMake the rover face the way it drives.
- Below the comment in
Update(), writeif (move != Vector3.zero), so a standing rover keeps its facing. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground