Face the Way You Move
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 42 of 63.
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
MediumThe bee flies from flower to flower. The ready-made Mover script flies it in straight lines, climbing or diving on the way, and rests it 1 second on each flower; leave Mover as it is. Write FaceMotion so that the bee faces the way it flies:
- It faces the way it moved since the last frame, seen from above.
- It stays upright: no nose up or down while it climbs or dives.
- While it rests, it keeps the facing it had, and nothing is logged.
The code goes in LateUpdate(), so Mover has already moved the bee for this frame. Press Play, 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.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall