FollowTrackingCamera.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using UnityEngine;
  2. public class FollowTrackingCamera : MonoBehaviour
  3. {
  4. // Camera target to look at.
  5. public Transform target;
  6. public Vector3 CameraRotation;
  7. // Exposed vars for the camera position from the target.
  8. public float height = 20f;
  9. public float distance = 20f;
  10. // Camera limits.
  11. public float min = 10f;
  12. public float max = 60;
  13. // Options.
  14. //public bool doRotate;
  15. public bool doZoom;
  16. // The movement amount when zooming.
  17. public float zoomStep = 30f;
  18. public float zoomSpeed = 5f;
  19. private float heightWanted;
  20. private float distanceWanted;
  21. // Result vectors.
  22. private Vector3 zoomResult;
  23. private Quaternion rotationResult;
  24. private Vector3 targetAdjustedPosition;
  25. void Start(){
  26. // Initialise default zoom vals.
  27. heightWanted = height;
  28. distanceWanted = distance;
  29. // Setup our default camera. We set the zoom result to be our default position.
  30. zoomResult = new Vector3(0f, height, -distance);
  31. }
  32. void LateUpdate(){
  33. // Check target.
  34. if( !target ){
  35. Debug.LogError("This camera has no target, you need to assign a target in the inspector.");
  36. return;
  37. }
  38. if( doZoom ){
  39. // Record our mouse input. If we zoom add this to our height and distance.
  40. float mouseInput = Input.GetAxis("Mouse ScrollWheel");
  41. heightWanted -= zoomStep * mouseInput;
  42. distanceWanted -= zoomStep * mouseInput;
  43. // Make sure they meet our min/max values.
  44. heightWanted = Mathf.Clamp(heightWanted, min, max);
  45. distanceWanted = Mathf.Clamp(distanceWanted, min, max);
  46. height = Mathf.Lerp(height, heightWanted, Time.deltaTime * zoomSpeed);
  47. distance = Mathf.Lerp(distance, distanceWanted, Time.deltaTime * zoomSpeed);
  48. // Post our result.
  49. zoomResult = new Vector3(0f, height, -distance);
  50. }
  51. // Convert the angle into a rotation.
  52. rotationResult = Quaternion.Euler(CameraRotation);
  53. // Set the camera position reference.
  54. targetAdjustedPosition = rotationResult * zoomResult;
  55. //targetAdjustedPosition = AnguloInicial * zoomResult;
  56. transform.position = target.position + targetAdjustedPosition;
  57. // Face the desired position.
  58. transform.LookAt(target);
  59. }
  60. }