SmoothFollowCShap.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class SmoothFollowCShap : MonoBehaviour
  5. {
  6. /*
  7. This camera smoothes out rotation around the y-axis and height.
  8. Horizontal Distance to the target is always fixed.
  9. There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves.
  10. For every of those smoothed values we calculate the wanted value and the current value.
  11. Then we smooth it using the Lerp function.
  12. Then we apply the smoothed values to the transform's position.
  13. */
  14. // The target we are following
  15. public Transform target;
  16. // The distance in the x-z plane to the target
  17. public float distance = 10.0f;
  18. // the height we want the camera to be above the target
  19. public float height = 5.0f;
  20. // How much we
  21. public float heightDamping = 0.5f;
  22. public float rotationDamping = 0.3f;
  23. private float _RefRotation = 0f;
  24. private float _RefHigh = 0f;
  25. void LateUpdate()
  26. {
  27. // Early out if we don't have a target
  28. if (!target)
  29. return;
  30. // Calculate the current rotation angles
  31. float wantedRotationAngle = target.eulerAngles.y;
  32. float wantedHeight = target.position.y + height;
  33. float currentRotationAngle = transform.eulerAngles.y;
  34. float currentHeight = transform.position.y;
  35. // Damp the rotation around the y-axis
  36. currentRotationAngle = Mathf.SmoothDampAngle(currentRotationAngle, wantedRotationAngle, ref _RefRotation, rotationDamping);
  37. // Damp the height
  38. currentHeight = Mathf.SmoothDamp(currentHeight, wantedHeight, ref _RefHigh, heightDamping);
  39. // Convert the angle into a rotation
  40. Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
  41. // Set the position of the camera on the x-z plane to:
  42. // distance meters behind the target
  43. transform.position = target.position;
  44. transform.position -= currentRotation * Vector3.forward * distance;
  45. // Set the height of the camera
  46. // transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
  47. //transform.position.Set(transform.position.x, currentHeight, transform.position.z);
  48. // Always look at the target
  49. transform.LookAt(target);
  50. }
  51. }