CamMouseOrbit.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using UnityEngine;
  2. public class CamMouseOrbit : MonoBehaviour
  3. {
  4. private float x = 0.0f;
  5. private float y = 0.0f;
  6. private float dist;
  7. private bool locked;
  8. public Transform target;
  9. public float distance = 10.0f;
  10. public float xSpeed = 5.0f;
  11. public float ySpeed = 2.5f;
  12. public float distSpeed = 10.0f;
  13. public float yMinLimit = -20.0f;
  14. public float yMaxLimit = 80.0f;
  15. public float distMinLimit = 5.0f;
  16. public float distMaxLimit = 50.0f;
  17. public float orbitDamping = 4.0f;
  18. public float distDamping = 4.0f;
  19. private void Awake()
  20. {
  21. ChangeCursor();
  22. dist = distance;
  23. }
  24. private void Start()
  25. {
  26. Vector3 angles = transform.eulerAngles;
  27. x = angles.y;
  28. y = angles.x;
  29. if (GetComponent<Rigidbody>())
  30. {
  31. GetComponent<Rigidbody>().freezeRotation = true;
  32. }
  33. }
  34. private void ChangeCursor()
  35. {
  36. Cursor.lockState = locked ? CursorLockMode.None : CursorLockMode.Locked;
  37. Cursor.visible = locked;
  38. }
  39. private void Update()
  40. {
  41. if(Input.GetMouseButtonDown(1))
  42. {
  43. locked = !locked;
  44. ChangeCursor();
  45. }
  46. }
  47. private void FixedUpdate()
  48. {
  49. if (!target || locked) return;
  50. x += Input.GetAxis("Mouse X") * xSpeed;
  51. y -= Input.GetAxis("Mouse Y") * ySpeed;
  52. distance -= Input.GetAxis("Mouse ScrollWheel") * distSpeed;
  53. y = ClampAngle(y, yMinLimit, yMaxLimit);
  54. distance = Mathf.Clamp(distance, distMinLimit, distMaxLimit);
  55. dist = Mathf.Lerp(dist, distance, distDamping * Time.deltaTime);
  56. transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(y, x, 0), Time.deltaTime * orbitDamping);
  57. transform.position = transform.rotation * new Vector3(0.0f, 0.0f, -dist) + target.position;
  58. }
  59. private float ClampAngle(float a, float min, float max)
  60. {
  61. while (max < min) max += 360.0f;
  62. while (a > max) a -= 360.0f;
  63. while (a < min) a += 360.0f;
  64. if (a > max)
  65. {
  66. if (a - (max + min) * 0.5 < 180.0)
  67. return max;
  68. else
  69. return min;
  70. }
  71. else
  72. return a;
  73. }
  74. }