Look Ahead
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 47 of 63.
A camera aimed at a moving target shows as much of where it has been as of where it is going. Aim at a point ahead of it instead: the target's position plus its velocity times a lead time in seconds. This camera on a stand beside a race track turns to follow the car and aims half a second ahead of it:
public Rigidbody car;
public float lead = 0.5f;
void LateUpdate()
{
Vector3 aim = car.position + car.linearVelocity * lead;
transform.LookAt(aim);
}At 20 units per second the aim point is 10 units in front of the car, at 4 units per second it is 2, and a car standing still is aimed at directly. The velocity is the car's real motion, so the point is in the right place in a skid or when reversing. transform.forward would not be: a reversing car's forward points away from where it is going, and a rolling ball's forward spins with it.
A follow camera can lead too: it frames a point ahead of its target instead of the target itself. When that point can flip to the other side, as when the player turns round, change the lead a little on each frame, or the whole view jumps at once.
Challenge
MediumThis side view follows the runner along x (the arrows run it left and right). Make the camera show more of where the runner is going:
- The camera sits
ahead(3) units in front of the runner along x, on the side the runner last moved toward. Before the runner first moves, it is centered on it. - When the runner turns round, the lead slides to the other side at
shiftSpeed(4) units per second instead of jumping. - When the runner stops, the camera keeps its lead.
- The camera's y and z stay as they are.
Press Play, run both ways, then Check.
Try it yourself
using UnityEngine;
public class LookAheadCamera : MonoBehaviour
{
public Transform player;
public float ahead = 3f;
public float shiftSpeed = 4f;
void LateUpdate()
{
// Lead the player by ahead units the way it last moved, sliding at shiftSpeed.
transform.position = new Vector3(player.position.x, transform.position.y, transform.position.z);
}
}
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