Skip to content

Instantly share code, notes, and snippets.

@aameralduais
Forked from GuilleUCM/SmoothFollow2D
Created August 6, 2017 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aameralduais/89493782165fb61c151b25073835aa46 to your computer and use it in GitHub Desktop.
Save aameralduais/89493782165fb61c151b25073835aa46 to your computer and use it in GitHub Desktop.
Unity:Camera:Smooth Follow 2D
using UnityEngine;
using System.Collections;
public class SmoothFollow2D : MonoBehaviour {
//offset from the viewport center to fix damping
public float m_DampTime = 10f;
public Transform m_Target;
public float m_XOffset = 0;
public float m_YOffset = 0;
private float margin = 0.1f;
void Start () {
if (m_Target==null){
m_Target = GameObject.FindGameObjectWithTag("Player").transform;
}
}
void Update() {
if(m_Target) {
float targetX = m_Target.position.x + m_XOffset;
float targetY = m_Target.position.y + m_YOffset;
if (Mathf.Abs(transform.position.x - targetX) > margin)
targetX = Mathf.Lerp(transform.position.x, targetX, 1/m_DampTime * Time.deltaTime);
if (Mathf.Abs(transform.position.y - targetY) > margin)
targetY = Mathf.Lerp(transform.position.y, targetY, m_DampTime * Time.deltaTime);
transform.position = new Vector3(targetX, targetY, transform.position.z);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment