unity 2d camera follow player code example

Example 1: camera follow player unity 2d

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

public class CameraController : MonoBehaviour
{
    //Object you want to follow
    public Transform target;
    
    //Set to z -10
    public Vector3 offset;
    
    //How much delay on the follow
    [Range(1, 10)]
    public float smoothing;

    private void FixedUpdate()
    {
        Follow();
    }

    void Follow()
    {
        Vector3 targetPosition = target.position + offset;
        Vector3 smoothPosition = Vector3.Lerp(transform.position, targetPosition, smoothing * Time.fixedDeltaTime);
        transform.position = smoothPosition;
    }
}

Example 2: how to make camera follow player unity 2d

public class CameraFollow : MonoBehaviour {

    public GameObject Target;
    private Vector3 Offset;


    // Start is called before the first frame update
    void Start() {

        Offset = transform.position - Target.transform.position;
        
    }

    // Update is called once per frame
    void Update() {
    
        transform.position = Target.transform.position+Offset;

        
    }
}

Example 3: camera 2d follow script

using UnityEngine;
using System.Collections;

public class FollowCamera : MonoBehaviour {

	public float interpVelocity;
	public float minDistance;
	public float followDistance;
	public GameObject target;
	public Vector3 offset;
	Vector3 targetPos;
	// Use this for initialization
	void Start () {
		targetPos = transform.position;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		if (target)
		{
			Vector3 posNoZ = transform.position;
			posNoZ.z = target.transform.position.z;

			Vector3 targetDirection = (target.transform.position - posNoZ);

			interpVelocity = targetDirection.magnitude * 5f;

			targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime); 

			transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);

		}
	}
}

Example 4: how to make a camera follow an object in unity 2d

public Transform player;  public Vector3 offset;    void Update ()   {      transform.position = new Vector3 (player.position.x + offset.x, player.position.y + offset.y, offset.z); // Camera follows the player with specified offset position  }