DragPreviewItem.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.EventSystems;
  4. using System;
  5. namespace Devdog.SciFiDesign.UI
  6. {
  7. public class DragPreviewItem : MonoBehaviour, IDragHandler, IPointerDownHandler, IEndDragHandler
  8. {
  9. public Transform previewItem;
  10. public float rotationSpeed = 1f;
  11. public bool doInertia = true;
  12. public float inertiaFallofSpeed = 1f;
  13. private Vector2 _inertia;
  14. public string controllerAxisX;
  15. public string controllerAxisY;
  16. public float controllerRotationSpeed = 10f;
  17. private bool _stoppedDragging = false;
  18. private float _timer = 0f;
  19. public void Update()
  20. {
  21. if (string.IsNullOrEmpty(controllerAxisX) == false)
  22. {
  23. var axis = Input.GetAxis(controllerAxisX);
  24. Rotate(new Vector3(axis, 0f, 0f), controllerRotationSpeed);
  25. }
  26. if (string.IsNullOrEmpty(controllerAxisY) == false)
  27. {
  28. var axis = Input.GetAxis(controllerAxisY);
  29. Rotate(new Vector3(0f, axis, 0f), controllerRotationSpeed);
  30. }
  31. if (doInertia == false)
  32. {
  33. return;
  34. }
  35. // Handle inertia of spin
  36. if (_stoppedDragging)
  37. {
  38. _timer += Time.deltaTime * inertiaFallofSpeed;
  39. _inertia = Vector2.Lerp(_inertia, Vector2.zero, _timer);
  40. Rotate(new Vector3(_inertia.y, -_inertia.x, 0f), _inertia.magnitude);
  41. // Stop handling interpolation update to avoid jitter.
  42. if (_inertia == Vector2.zero)
  43. {
  44. _stoppedDragging = false;
  45. }
  46. }
  47. }
  48. public void OnPointerDown(PointerEventData eventData)
  49. {
  50. _stoppedDragging = false;
  51. _inertia = Vector2.zero;
  52. }
  53. public void OnDrag(PointerEventData eventData)
  54. {
  55. _stoppedDragging = false;
  56. var d = eventData.delta.normalized;
  57. Rotate(new Vector3(d.y, -d.x, 0f), eventData.delta.magnitude * rotationSpeed);
  58. }
  59. protected virtual void Rotate(Vector3 rotation, float angle)
  60. {
  61. previewItem.RotateAround(previewItem.position, rotation, angle);
  62. }
  63. public void OnEndDrag(PointerEventData eventData)
  64. {
  65. _stoppedDragging = true;
  66. _inertia = eventData.delta * rotationSpeed;
  67. _timer = 0f;
  68. }
  69. }
  70. }