ThreeDofRayCaster.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Rokid.UXR.Utility;
  2. using UnityEngine;
  3. namespace Rokid.UXR.Interaction
  4. {
  5. /// <summary>
  6. /// 射线投射器 Only Use Station Pro
  7. /// </summary>
  8. public class ThreeDofRayCaster : BaseRayCaster
  9. {
  10. [SerializeField]
  11. public float maxDragDistance = 10;
  12. [SerializeField]
  13. public float minDragDistance = 0.5f;
  14. private bool dragLock;
  15. private float curHitPointDis;
  16. private Vector3 curHitPoint;
  17. private Vector3 targetHitPoint;
  18. private Vector3 oriRayPos;
  19. protected override void Init()
  20. {
  21. base.Init();
  22. if (inputOverride == null)
  23. {
  24. inputOverride = GetComponent<NormalInput>();
  25. if (inputOverride == null)
  26. {
  27. inputOverride = gameObject.AddComponent<NormalInput>();
  28. }
  29. }
  30. }
  31. protected override bool ProcessDrag(Ray ray)
  32. {
  33. // 计算拖拽点的目标位置
  34. CalDeltaZ();
  35. targetHitPoint = rayOrigin.position + ray.direction * curHitPointDis;
  36. var delta = (targetHitPoint - oriHitPoint);
  37. m_SelectedObj.SendMessageUpwards(drag, delta, SendMessageOptions.DontRequireReceiver);
  38. curHitPoint = oriHitPoint = targetHitPoint;
  39. return true;
  40. }
  41. protected override bool CanDrag(Vector3 delta)
  42. {
  43. bool canDrag = !dragLock && !dragging && (m_SelectedObj.GetComponent<IRayBeginDrag>() != null || m_SelectedObj.GetComponentInParent<IRayBeginDrag>() != null);
  44. dragLock = true;
  45. return canDrag;
  46. }
  47. protected override bool DragRelease()
  48. {
  49. bool release = dragging && input.GetMouseButtonDown(0);
  50. return release;
  51. }
  52. private void LateUpdate()
  53. {
  54. if (!dragging && input.GetMouseButtonUp(0))
  55. {
  56. dragLock = false;
  57. }
  58. }
  59. protected override void OnFirstSelect()
  60. {
  61. oriHitPoint = result.worldPosition;
  62. oriRayPos = ray.origin;
  63. }
  64. private void CalDeltaZ()
  65. {
  66. if (Utils.IsAndroidPlatfrom())
  67. {
  68. var forward = Input.GetKey(KeyCode.UpArrow) ? 1 : (Input.GetKey(KeyCode.DownArrow) ? -1 : 0);
  69. Vector3 deltaZ = ray.direction * forward * 0.05f;
  70. Vector3 deltaRayPos = ray.origin - oriRayPos;
  71. oriRayPos = ray.origin;
  72. curHitPoint = oriHitPoint + deltaRayPos;
  73. curHitPointDis = Mathf.Clamp(Vector3.Distance(curHitPoint + deltaZ, ray.origin), minDragDistance, maxDragDistance);
  74. }
  75. else
  76. {
  77. Vector3 deltaZ = ray.direction * Input.mouseScrollDelta.y * 0.5f;
  78. Vector3 deltaRayPos = ray.origin - oriRayPos;
  79. oriRayPos = ray.origin;
  80. curHitPoint = oriHitPoint + deltaRayPos;
  81. curHitPointDis = Mathf.Clamp(Vector3.Distance(curHitPoint + deltaZ, ray.origin), minDragDistance, maxDragDistance);
  82. }
  83. }
  84. }
  85. }