You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.7 KiB

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