TransformRotationFromMousePosition.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace Devdog.SciFiDesign.UI
  4. {
  5. public class TransformRotationFromMousePosition : MonoBehaviour
  6. {
  7. [SerializeField]
  8. private Vector3 _rotation;
  9. private float _prevX;
  10. private float _prevY;
  11. protected void Update()
  12. {
  13. if (Mathf.Approximately(Input.mousePosition.x, _prevX) == false || Mathf.Approximately(Input.mousePosition.y, _prevY) == false)
  14. {
  15. // Cursor moved
  16. var normalized = new Vector2(Input.mousePosition.x / Screen.width, Input.mousePosition.y / Screen.height);
  17. normalized.x -= 0.5f;
  18. normalized.x *= 2f;
  19. normalized.y -= 0.5f;
  20. normalized.y *= 2f;
  21. var rot = _rotation;
  22. rot.x *= normalized.y;
  23. rot.y *= normalized.x;
  24. transform.rotation = Quaternion.Euler(rot);
  25. }
  26. _prevX = Input.mousePosition.x;
  27. _prevY = Input.mousePosition.y;
  28. }
  29. }
  30. }