2D Camera Follow code example
Example 1: 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;
void Start () {
targetPos = transform.position;
}
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 2: 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);