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.

62 lines
2.0 KiB

  1. /*
  2. This camera smoothes out rotation around the y-axis and height.
  3. Horizontal Distance to the target is always fixed.
  4. 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.
  5. For every of those smoothed values we calculate the wanted value and the current value.
  6. Then we smooth it using the Lerp function.
  7. Then we apply the smoothed values to the transform's position.
  8. */
  9. // The target we are following
  10. var target : Transform;
  11. // The distance in the x-z plane to the target
  12. var distance = 10.0;
  13. // the height we want the camera to be above the target
  14. var height = 5.0;
  15. // How much we
  16. var heightDamping = 2.0;
  17. var rotationDamping = 3.0;
  18. // Place the script in the Camera-Control group in the component menu
  19. @script AddComponentMenu("Camera-Control/Smooth Follow")
  20. function Start(){
  21. distance = target.position.z - transform.position.z;
  22. height = transform.position.y - target.position.y;
  23. }
  24. function LateUpdate () {
  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.y = currentHeight;
  45. // Always look at the target
  46. transform.LookAt (target);
  47. }