Published on

Implement a camera that smoothly follows the object.

Authors
  • Evelyn
    Full-time IndieDev.
    I'm Japanese, so please forgive me if my English is strange.

Please share this article if you like!

Hello!

Today, let's implement a camera that follows the movement of an object.

I think this can be applied to not only cameras, but also objects that follow the player in various cases, so please read to the end.

The image of the code used in this article looks like this.

Table of Contents

Code and description

The whole code looks like the following.

TrailCamera.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TrailCamera : MonoBehaviour
{
    public Transform target;
    public float trailDistance = 5.0f;
    public float heightOffset = 3.0f;

    void LateUpdate()
    {
        Vector3 followPos = target.position - target.forward * trailDistance;

        followPos.y += heightOffset;
        transform.position = Vector3.Lerp(transform.position, followPos, Time.deltaTime);

        transform.LookAt(target.transform);
    }
}

Let's take a closer look at each.

The first step is to define the public variables.

"target" is a Transform type and is used to get the location information of the target.

"trailDistance" is the distance to the target.

The heightOffset controls how much higher than the target it should be.

public Transform target;
public float trailDistance = 5.0f;
public float heightOffset = 3.0f;

We want to move the camera after the object has been completely moved, so we will describe the process in the LateUpdate method.

void LateUpdate()

This is the part that calculates the next position of the camera.

Vector3 followPos = target.position - target.forward * trailDistance;

followPos.y += heightOffset;
transform.position = Vector3.Lerp(transform.position, followPos, Time.deltaTime);

Finally, make sure that the camera is facing the object.

transform.LookAt(target.transform);

Summary of this article

In this article, I explained about cameras that chase objects smoothly.

How did you like it? I hope you will try it in your games.

If you like the content of this article, please follow us on twitter or subscribe to our youtube channel.

Thank you for reading to the end.

Please share this article if you like!