Menu
CoddyTech

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 icon

Challenge

Medium

Make the side camera show more of where the runner is going.

  1. In LateUpdate(), compare the runner's x with lastX: moving right sets direction to 1, left to -1, standing still leaves it.
  2. Slide shift = Mathf.MoveTowards(shift, direction * ahead, shiftSpeed * Time.deltaTime);.
  3. 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

Practice on your own: Unity playground