How to make camera follow the player in Unity 3d?

In this article we will learn about. How do you make the camera follow the player in Unity 3d?

And, we’ll enable the camera to follow the player around the play field by writing a simple C# script.

Create a script for Camera.

click on Main Camera –> go to Inspector window –> click on Add components –>new Script –>Name the script(CameraController).

OR

Go to inside the Project Window.

right-click–> create –> C# Script

Rename the file as CameraController

Now, paste the following code into your script.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public GameObject player;        //Public variable to store a reference to the player game object


    private Vector3 offset;            //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start () 
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate () 
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}

If you were created script from Project window then drag and drop the script on Main Camera. It will add the script to main Camera.

Now, Drag and Drop the Player into Player field inside on CameraController script inside the Main Camera Inspector window.

Now, Run the project and you will get the camera follow the Player movement.

Hope this will be helpfull for you.

Thank You.

6 thoughts on “How to make camera follow the player in Unity 3d?

  1. I am making a game that has to do with driving but when I go up a hill the camera stays flat and does not follow or go up the hill, How do I fix this?

  2. Excellent site you’ve got here.. It’s hard to find good quality writing like yours these days.
    I honestly appreciate people like you! Take care!!

Leave a Reply

Your email address will not be published. Required fields are marked *