Menu
CoddyTech

Face the Way You Move

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 44 of 71.

transform.LookAt needs a point to look at. Often what you have is a direction instead: a velocity, the wind, the way something moved. Quaternion.LookRotation(direction) returns the rotation whose forward (the blue z arrow) points along that direction, with the object's up kept toward the world's up. An arrow shot into the air points up at first and tips over as it falls, because its velocity does:

Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void Update()
{
    if (rb.linearVelocity != Vector3.zero)
    {
        transform.rotation = Quaternion.LookRotation(rb.linearVelocity);
    }
}

Only the direction counts, not the length: (1, 0, 2) and (3, 0, 6) give the same rotation. A zero vector has no direction, so LookRotation(Vector3.zero) logs Look rotation viewing vector is zero and returns Quaternion.identity, which snaps the object to face +z. That is why the arrow checks first: once it stops, it keeps the facing it had. LookAt(target.position) gives the same rotation as LookRotation(target.position - transform.position).

The direction's up and down part tips the forward up or down with it. For something that must stay upright, such as a walker going up a slope, set the direction's y to 0 first, so the object turns only around y. A second argument, LookRotation(direction, Vector3.up), says which way is up; Vector3.up is what you get without it.

challenge icon

Challenge

Medium

Make the bee face the way it flies, staying upright.

  1. In LateUpdate(), set Vector3 direction = transform.position - lastPosition; and direction.y = 0;.
  2. Only when direction != Vector3.zero, set transform.rotation = Quaternion.LookRotation(direction);, so a resting bee keeps its facing.
  3. Last, store transform.position in lastPosition.

Press Play: the bee turns toward each flower it flies to. Then Check.

Try it yourself

using UnityEngine;

public class FaceMotion : MonoBehaviour
{
    Vector3 lastPosition;

    void Start()
    {
        lastPosition = transform.position;
    }

    void LateUpdate()
    {
        // Face the way the bee moved since the last frame.
    }
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground