1 using System;
2 using
UnityEngine;
3
4 namespace
UnityStandardAssets._2D
5 {
6     
public class Camera2DFollow : MonoBehaviour
7     {
8         
public Transform target;
9         
public float damping = 1;
10         
public float lookAheadFactor = 3;
11         
public float lookAheadReturnSpeed = 0.5f;
12         
public float lookAheadMoveThreshold = 0.1f;
13
14         
private float m_OffsetZ;
15         
private Vector3 m_LastTargetPosition;
16         
private Vector3 m_CurrentVelocity;
17         
private Vector3 m_LookAheadPos;
18
19         
// Use this for initialization
20         
private void Start()
21         {
22             m_LastTargetPosition = target.position;
23             m_OffsetZ = (transform.position - target.position).z;
24             transform.parent =
null;
25         }
26
27
28         
// Update is called once per frame
29         
private void Update()
30         {
31             
// only update lookahead pos if accelerating or changed direction
32             
float xMoveDelta = (target.position - m_LastTargetPosition).x;
33
34             
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
35
36             
if (updateLookAheadTarget)
37             {
38                 m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
39             }
40             
else
41             {
42                 m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
43             }
44
45             Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
46             Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos,
ref m_CurrentVelocity, damping);
47
48             transform.position = newPos;
49
50             m_LastTargetPosition = target.position;
51         }
52     }
53 }