Skip to content

Instantly share code, notes, and snippets.

@arxae
Created August 22, 2014 10:53
Show Gist options
  • Save arxae/0d5704c91627c6d8cbcd to your computer and use it in GitHub Desktop.
Save arxae/0d5704c91627c6d8cbcd to your computer and use it in GitHub Desktop.
[Unity] Smoothly follows the target. Attach to the camera
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform Target;
public float Damping = 1f;
public float LookAheadFactor = 3f;
public float LookAheadReturnSpeed = 0.5f;
public float LookAheadMoveTreshold = 0.1f;
private float offsetZ;
private Vector3 lastTargetPosition;
private Vector3 currentVelocity;
private Vector3 lookAheadPos;
void Start()
{
lastTargetPosition = Target.position;
offsetZ = (transform.position - Target.position).z;
transform.parent = null;
}
void Update()
{
float xMoveDelta = (Target.position - lastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > LookAheadMoveTreshold;
if (updateLookAheadTarget)
{
lookAheadPos = LookAheadFactor * Vector3.right * Mathf.Sign(xMoveDelta);
}
else
{
lookAheadPos = Vector3.MoveTowards(lookAheadPos, Vector3.zero, Time.deltaTime * LookAheadReturnSpeed);
}
Vector3 aheadTargetPos = Target.position + lookAheadPos + Vector3.forward * offsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref currentVelocity, Damping);
transform.position = newPos;
lastTargetPosition = Target.position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment