Look Ahead
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 49 of 71.
A camera centred on a moving player shows as much of where it has been as of where it is going. A side view can lead instead: sit a few units in front of the player, on the side it is heading toward.
The side flips when the player turns round, and a lead that flips at once makes the whole view jump. So keep the lead in a field and slide it toward its new value with Mathf.MoveTowards, a little on each frame. This boat camera leads by 2 units and slides at 3 units per second:
float lead;
float heading = 1f; // 1 sailing right, -1 sailing left
void LateUpdate()
{
lead = Mathf.MoveTowards(lead, heading * 2f, 3f * Time.deltaTime);
transform.position = new Vector3(boat.position.x + lead, transform.position.y, transform.position.z);
}The heading is the way the boat last moved: compare its x with its x on the last frame, and leave the heading alone on a frame when it did not move, so a boat at rest keeps its lead.
Challenge
MediumMake the side camera show more of where the runner is going.
- In
LateUpdate(), compare the runner's x withlastX: moving right setsdirectionto 1, left to -1, standing still leaves it. - Slide
shift = Mathf.MoveTowards(shift, direction * ahead, shiftSpeed * Time.deltaTime);. - Set the camera's x to
player.position.x + shift, keeping y and z.
Press Play and 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);
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground