Skip to content

Instantly share code, notes, and snippets.

@GuilleUCM
Created April 2, 2015 09:46
Show Gist options
  • Save GuilleUCM/0627c64630b745f70bd2 to your computer and use it in GitHub Desktop.
Save GuilleUCM/0627c64630b745f70bd2 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