Digital Leadership & Soft Skills

Unity | Smooth camera follow 2D

Published by Pavel Nakonechnyy on in GameDev.
Unity | Smooth camera follow 2D

Camera with this small script will follow Target with gap depending on its speed.


using System.Collections;

using UnityEngine;

public class SmoothFollow2D : MonoBehaviour {
    public Transform Target;
    public Vector3 Offset;
    public float Velocity;
    public float MinDistance;

    // Update is called once per frame
    void LateUpdate() {
        if (Target == null) {
            return;
        }

        var targetPos = Target.transform.position + Offset;

        if (Vector3.Distance(transform.position, targetPos) < MinDistance) {
            return;
        }
        var newPos = Vector3.Lerp(transform.position, targetPos, Velocity * Time.fixedDeltaTime);
        transform.Translate(transform.InverseTransformPoint(newPos));
    }
}
265