MouseOrbitController.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using UnityEngine;
  2. namespace MaterializationFX.Scripts.Utils
  3. {
  4. internal sealed class MouseOrbitController : 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 YMinLimit = 20f;
  11. public float YMaxLimit = 80f;
  12. public float DistanceMin = .5f;
  13. public float DistanceMax = 15f;
  14. private float _x;
  15. private float _y;
  16. private void Start()
  17. {
  18. var angles = transform.eulerAngles;
  19. _x = angles.y;
  20. _y = angles.x;
  21. }
  22. private void LateUpdate()
  23. {
  24. if (!Input.GetMouseButton(0))
  25. return;
  26. _x += Input.GetAxis("Mouse X") * XSpeed * Distance * 0.02f;
  27. _y -= Input.GetAxis("Mouse Y") * YSpeed * 0.02f;
  28. _y = ClampAngle(_y, YMinLimit, YMaxLimit);
  29. var rotation = Quaternion.Euler(_y, _x, 0);
  30. Distance -= Input.GetAxis("Mouse ScrollWheel") * 5;
  31. var negDistance = new Vector3(0.0f, 0.0f, -Distance);
  32. var position = rotation * negDistance + Target.position;
  33. transform.rotation = rotation;
  34. transform.position = position;
  35. }
  36. private static float ClampAngle(float angle, float min, float max)
  37. {
  38. if (angle < -360F)
  39. angle += 360F;
  40. if (angle > 360F)
  41. angle -= 360F;
  42. return Mathf.Clamp(angle, min, max);
  43. }
  44. }
  45. }