SmoothFollow.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. #pragma warning disable 649
  3. namespace UnityStandardAssets.Utility
  4. {
  5. public class SmoothFollow : MonoBehaviour
  6. {
  7. // The target we are following
  8. [SerializeField]
  9. private Transform target;
  10. // The distance in the x-z plane to the target
  11. [SerializeField]
  12. private float distance = 10.0f;
  13. // the height we want the camera to be above the target
  14. [SerializeField]
  15. private float height = 5.0f;
  16. [SerializeField]
  17. private float rotationDamping;
  18. [SerializeField]
  19. private float heightDamping;
  20. // Use this for initialization
  21. void Start() { }
  22. // Update is called once per frame
  23. void LateUpdate()
  24. {
  25. // Early out if we don't have a target
  26. if (!target)
  27. return;
  28. // Calculate the current rotation angles
  29. var wantedRotationAngle = target.eulerAngles.y;
  30. var wantedHeight = target.position.y + height;
  31. var currentRotationAngle = transform.eulerAngles.y;
  32. var currentHeight = transform.position.y;
  33. // Damp the rotation around the y-axis
  34. currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
  35. // Damp the height
  36. currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
  37. // Convert the angle into a rotation
  38. var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
  39. // Set the position of the camera on the x-z plane to:
  40. // distance meters behind the target
  41. transform.position = target.position;
  42. transform.position -= currentRotation * Vector3.forward * distance;
  43. // Set the height of the camera
  44. transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z);
  45. // Always look at the target
  46. transform.LookAt(target);
  47. }
  48. }
  49. }