Tag Archives: make

Making the camera follow the player in a 2D Unity game with code

This tutorial will show you how to write a script in C# code that will make the camera follow the player in a 2D Unity game. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

  public GameObject player;
  public float offset;
  private Vector3 playerPosition;
  public float offsetSmoothing;

  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
    playerPosition = new Vector3 (player.transform.position.x, transform.position.y, transform.position.z);
    if (player.transform.localScale.x > 0f) {
      playerPosition = new Vector3 (playerPosition.x + offset, playerPosition.y, playerPosition.z);
    }
    else {
      playerPosition = new Vector3(playerPosition.x - offset, playerPosition.y, playerPosition.z);
    }

    transform.position = Vector3.Lerp (transform.position, playerPosition, offsetSmoothing * Time.deltaTime);
  }
}

Next tutorial: Stopping the player from sticking to the edge of platforms and walls