Harlepengren

Learn How to Create a Simple Camera Follow Script in Unity

Every time I start a new Unity project, I feel like I write the camera follow script from scratch. Although it is important for the camera movement to match the project, sometimes, you just need a basic camera. This post provides a basic camera movement script that follows another game object.

Here is the code:

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    [SerializeField] private GameObject target;
    [SerializeField] private float speed;
    [SerializeField] private float threshold;
    [SerializeField] private Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        Vector3 target_position = target.transform.position + offset;
        Vector3 cam_position = transform.position;

        // Get a vector in direction of target
        Vector3 direction = target_position - cam_position;
        direction.y = 0;

        // Only move if the movement is significant enough
        if(direction.magnitude > threshold)
        {
            direction.Normalize();

            cam_position += direction * speed * Time.deltaTime;
            transform.position = cam_position;
        }
    }
}

Class Variables

We start by creating four instance variables.

[SerializeField] private GameObject target;
[SerializeField] private float speed;
[SerializeField] private float threshold;
[SerializeField] private Vector3 offset;

Next, we add the SerializeField attribute to expose the variables to the Unity interface. Alternatively, we could declare these variables as public. However, to keep good class design, I prefer for these to be private or protected. In addition, I prefer not to give default values in code. If you provide default values, then the starting value can be changed in the Unity interface. Subsequent changes to the default values in code will not change the values in the interface, which can be confusing.

  • target: the object we want to follow
  • speed: how fast the camera should move
  • threshold: when are we close enough to the target object
  • Offset: how far away from the object should we stay. (0,0,0) would be right above the object. For example, I am using (0,0,-4) for my current project. 

Update Function

Next, we create the update function. We create three variables (all of type Vector3):

  • target_position: position of the target object
  • cam_position: position of the camera (or more broadly the object to which this script is attached)
  • direction: the direction the camera should move

To start off with, we get the current position of the target. However, we add our offset to the target. This reflects the fact that our target position is slightly offset from the target. Next, we get the current cam_position.

Vector3 target_position = target.transform.position + offset;
Vector3 cam_position = transform.position;

We calculate direction by simple vector math, target_position – cam_position. We then set the y value of direction to 0. In my case, I want the camera to stay at the same height. However, if your map has variation in height, you may want to change this. You could also add additional instance variables that allow you to lock or unlock different axes.

// Get a vector in direction of target
Vector3 direction = target_position - cam_position;
direction.y = 0;

Next, we get the magnitude of the direction and only move if the magnitude of the direction is bigger than our threshold. Without this, the camera will get close to the target position and continue to bounce around. You can test this by setting the threshold to 0.

Inside the if statement, we will normalize our direction. We then multiply the normalized direction by the speed and amount of time that passed from our previous frame (Time.deltaTime). We add the result to our cam_position.

Finally, we set the transform.position to cam_position.

// Only move if the movement is significant enough
if(direction.magnitude > threshold)
{
  direction.Normalize();

  cam_position += direction * speed * Time.deltaTime;
  transform.position = cam_position;
}

Conclusion

This script is very simple. However, if it can help at least one person speed up their game development, then posting it was worth it. Let me know in the comments if there are other scripts that you find yourself writing over and over.

One Comment

Comments are closed.