MouseOrbit.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using UnityEngine;
  2. using System.Collections;
  3. //[AddComponentMenu("Camera-Control/Mouse drag Orbit with zoom")]
  4. public class MouseOrbit : MonoBehaviour
  5. {
  6. public Transform target;
  7. public float distance = 5.0f;
  8. public float xSpeed = 120.0f;
  9. public float ySpeed = 120.0f;
  10. public float scrollSpeed = 1f;
  11. public float yMinLimit = -20f;
  12. public float yMaxLimit = 80f;
  13. public float distanceMin = .5f;
  14. public float distanceMax = 15f;
  15. public float smoothTime = 2f;
  16. float rotationYAxis = 0.0f;
  17. float rotationXAxis = 0.0f;
  18. float velocityX = 0.0f;
  19. float velocityY = 0.0f;
  20. private bool start = true;
  21. // Use this for initialization
  22. void Start()
  23. {
  24. Vector3 angles = transform.eulerAngles;
  25. rotationYAxis = angles.y;
  26. rotationXAxis = angles.x;
  27. // Make the rigid body not change rotation
  28. // if (rigidbody)
  29. // {
  30. // rigidbody.freezeRotation = true;
  31. // }
  32. }
  33. void LateUpdate()
  34. {
  35. if (target)
  36. {
  37. if (Input.GetMouseButton(1))
  38. {
  39. start = false;
  40. velocityX += xSpeed * Input.GetAxis("Mouse X") * 0.02f;
  41. velocityY += ySpeed * Input.GetAxis("Mouse Y") * 0.02f;
  42. }
  43. if (start) {
  44. return;
  45. }
  46. rotationYAxis += velocityX;
  47. rotationXAxis -= velocityY;
  48. rotationXAxis = ClampAngle(rotationXAxis, yMinLimit, yMaxLimit);
  49. //Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
  50. Quaternion toRotation = Quaternion.Euler (rotationXAxis, rotationYAxis, 0);
  51. Quaternion rotation = toRotation;
  52. Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
  53. Vector3 position = rotation * negDistance + target.position;
  54. transform.rotation = rotation;
  55. transform.position = position;
  56. velocityX = Mathf.Lerp(velocityX, 0, Time.deltaTime * smoothTime);
  57. velocityY = Mathf.Lerp(velocityY, 0, Time.deltaTime * smoothTime);
  58. float wheel = Input.GetAxis("Mouse ScrollWheel");
  59. if (wheel < 0f && distance < distanceMax)
  60. {
  61. // scroll down
  62. distance += scrollSpeed;
  63. }
  64. else if (wheel > 0f && distance > distanceMin)
  65. {
  66. // scroll up
  67. distance -= scrollSpeed;
  68. }
  69. }
  70. }
  71. public static float ClampAngle(float angle, float min, float max)
  72. {
  73. if (angle < -360F)
  74. angle += 360F;
  75. if (angle > 360F)
  76. angle -= 360F;
  77. return Mathf.Clamp(angle, min, max);
  78. }
  79. }