Camera2DFollow.cs 1.7 KB

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