SCInputModule.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. using UnityEngine.EventSystems;
  8. namespace SC.XR.Unity.Module_InputSystem {
  9. public class SCInputModule : StandaloneInputModule {
  10. public static SCInputModule Instance { get; private set; }
  11. public static bool IsRayCastResultsSortByDistance = false;
  12. private Camera mRayCasterCamera;
  13. public Camera RayCasterCamera {
  14. get {
  15. if(mRayCasterCamera == null) {
  16. mRayCasterCamera = EnsureUIEventCamera();
  17. }
  18. return mRayCasterCamera;
  19. }
  20. }
  21. private PhysicsRaycaster mPhysicsRaycaster;
  22. public PhysicsRaycaster PhysicsRaycaster {
  23. get {
  24. if(mPhysicsRaycaster == null) {
  25. mPhysicsRaycaster = EnsurePhysicsRaycaster();
  26. }
  27. return mPhysicsRaycaster;
  28. }
  29. }
  30. public LayerMask layerMask;
  31. public float maxDetectDistance=0;
  32. Vector3? lastMousePoint3d;
  33. Vector2 newPos, lastPosition;
  34. Vector3 viewportPos = new Vector3(0.5f, 0.5f, 1.0f);
  35. protected override void Start() {
  36. base.Start();
  37. if(Instance) {
  38. DestroyImmediate(this);
  39. return;
  40. }
  41. DontDestroyOnLoad(gameObject);
  42. Instance = this;
  43. }
  44. public override void Process() {
  45. }
  46. public virtual void ProcessCS(SCPointEventData scPointEventData, Transform posture, int layerMask = 1 << 8, float maxDetectDistance = 30,bool isSimlate=false, RaycastResult simlateResult=new RaycastResult()) {
  47. //if(!eventSystem.isFocused)
  48. // return;
  49. bool usedEvent = SendUpdateEventToSelectedObject();
  50. ProcessSCEventInit(scPointEventData, posture, layerMask, maxDetectDistance);
  51. ProcessSCEvent(scPointEventData, isSimlate, simlateResult);
  52. if(eventSystem.sendNavigationEvents) {
  53. if(!usedEvent)
  54. usedEvent |= SendMoveEventToSelectedObject();
  55. if(!usedEvent)
  56. SendSubmitEventToSelectedObject();
  57. }
  58. }
  59. void ProcessSCEventInit(SCPointEventData scPointEventData, Transform posture, int layerMask, float maxDetectDistance) {
  60. if(this.layerMask.value != 0) {
  61. layerMask = this.layerMask;
  62. }
  63. if(this.maxDetectDistance > 0) {
  64. maxDetectDistance = this.maxDetectDistance;
  65. }
  66. PhysicsRaycaster.eventMask = layerMask;
  67. RayCasterCamera.cullingMask = layerMask;
  68. RayCasterCamera.farClipPlane = maxDetectDistance;
  69. RayCasterCamera.transform.position = posture.position; // posture.position;// Vector3.Lerp(RayCasterCamera.transform.position, targetDetectBase.transform.position,0.3f); //targetDetectBase.transform.position;
  70. RayCasterCamera.transform.rotation = posture.rotation;
  71. ///Canvas分配wrold Camera
  72. foreach(var canvas in CanvasCollection.CanvasList) {
  73. canvas.worldCamera = RayCasterCamera;
  74. }
  75. newPos = SCInputModule.Instance.RayCasterCamera.ViewportToScreenPoint(viewportPos);
  76. // Populate initial data or drag data
  77. if(lastMousePoint3d == null) {
  78. // For the first event, use the same position for 'last' and 'new'.
  79. lastPosition = newPos;
  80. } else {
  81. // Otherwise, re-project the last pointer position.
  82. lastPosition = SCInputModule.Instance.RayCasterCamera.WorldToScreenPoint(lastMousePoint3d.Value);
  83. }
  84. // Save off the 3D position of the cursor.
  85. lastMousePoint3d = SCInputModule.Instance.RayCasterCamera.ViewportToWorldPoint(viewportPos);
  86. scPointEventData.delta = newPos - lastPosition;
  87. scPointEventData.position = newPos;
  88. if(RayCasterCamera != null && Application.platform != RuntimePlatform.Android) {
  89. Ray ray = new Ray();
  90. ray = RayCasterCamera.ScreenPointToRay(scPointEventData.position);
  91. Debug.DrawRay(ray.origin, ray.direction * maxDetectDistance, Color.blue);
  92. }
  93. }
  94. protected static RaycastResult FindFirstRaycastByDistance(List<RaycastResult> candidates) {
  95. candidates.Sort(s_RaycastComparer);
  96. return FindFirstRaycast(candidates);
  97. }
  98. private static readonly Comparison<RaycastResult> s_RaycastComparer = RaycastComparer;
  99. private static int RaycastComparer(RaycastResult lhs, RaycastResult rhs) {
  100. return lhs.distance.CompareTo(rhs.distance);
  101. }
  102. /// <summary>
  103. /// Process all mouse events.
  104. /// </summary>
  105. protected void ProcessSCEvent(SCPointEventData scPointEventData, bool isSimlate = false, RaycastResult simlateResult = new RaycastResult()) {
  106. scPointEventData.MouseButtonEventData.buttonData = scPointEventData;
  107. scPointEventData.MouseButtonEventData.buttonState = StateForMouseButton(scPointEventData.inputDevicePartBase);
  108. if(isSimlate) {
  109. scPointEventData.pointerCurrentRaycast = simlateResult;
  110. } else {
  111. eventSystem.RaycastAll(scPointEventData, m_RaycastResultCache);
  112. if (!IsRayCastResultsSortByDistance) {
  113. scPointEventData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache);
  114. } else {
  115. scPointEventData.pointerCurrentRaycast = FindFirstRaycastByDistance(m_RaycastResultCache);
  116. }
  117. m_RaycastResultCache.Clear();
  118. }
  119. scPointEventData.Forward = RayCasterCamera.transform.forward;
  120. if(scPointEventData.MouseButtonEventData.PressedThisFrame() && scPointEventData.pointerCurrentRaycast.gameObject) {
  121. scPointEventData.HitPointerRelativeRayCasterCamera = RayCasterCamera.transform.InverseTransformPoint(scPointEventData.pointerCurrentRaycast.worldPosition);
  122. scPointEventData.Position3D = scPointEventData.PressPosition3D = RayCasterCamera.transform.TransformPoint(scPointEventData.HitPointerRelativeRayCasterCamera);
  123. scPointEventData.pressForward = RayCasterCamera.transform.forward;
  124. scPointEventData.DownPressGameObject = scPointEventData.pointerCurrentRaycast.gameObject;
  125. } else if(scPointEventData.MouseButtonEventData.ReleasedThisFrame()) {
  126. scPointEventData.HitPointerDeltaDragObjCenter = scPointEventData.HitPointerRelativeRayCasterCamera = scPointEventData.dragObjPosition = Vector3.zero;
  127. scPointEventData.Position3D = Vector3.zero;
  128. scPointEventData.PressPosition3D = Vector3.zero;
  129. scPointEventData.DownPressGameObject = null;
  130. scPointEventData.pressForward = Vector3.zero;
  131. scPointEventData.downtimer = 0;
  132. }
  133. if(scPointEventData.DownPressGameObject) {
  134. scPointEventData.downtimer += Time.deltaTime;
  135. scPointEventData.Position3D = RayCasterCamera.transform.TransformPoint(scPointEventData.HitPointerRelativeRayCasterCamera);
  136. }
  137. // Process the first mouse button fully
  138. ProcessMousePress(scPointEventData.MouseButtonEventData);
  139. ProcessMove(scPointEventData);
  140. if(scPointEventData.MouseButtonEventData.PressedThisFrame() && scPointEventData.pointerCurrentRaycast.gameObject && scPointEventData.pointerDrag) {
  141. ///碰撞点指向碰撞物体中心的向量
  142. scPointEventData.HitPointerDeltaDragObjCenter = scPointEventData.pointerDrag.transform.position - scPointEventData.pointerCurrentRaycast.worldPosition;
  143. ///第一次赋值 ,must
  144. scPointEventData.dragObjPosition = scPointEventData.HitPointerDeltaDragObjCenter + scPointEventData.Position3D;
  145. }
  146. ///必须在ProcessDrag前,否则,延迟一帧导致停顿感
  147. if(scPointEventData.dragging) {
  148. scPointEventData.dragObjPosition = scPointEventData.HitPointerDeltaDragObjCenter + scPointEventData.Position3D;
  149. }
  150. ///拖拽不启动阈值,否则不能触发IDragHandler
  151. //scPointEventData.useDragThreshold = false;
  152. ProcessDrag(scPointEventData);
  153. ///更新dragHitPinterPosition,必须在ProcessDrag后,ProcessDrag调用的DragHandler可能会更改PointerDrag对象的Transform
  154. if(scPointEventData.dragging) {
  155. scPointEventData.dragAnchorPosition3D = scPointEventData.pointerDrag.transform.position - scPointEventData.HitPointerDeltaDragObjCenter;
  156. } else {
  157. scPointEventData.dragAnchorPosition3D = Vector3.zero;
  158. }
  159. if(!Mathf.Approximately(scPointEventData.scrollDelta.sqrMagnitude, 0.0f)) {
  160. var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(scPointEventData.pointerCurrentRaycast.gameObject);
  161. ExecuteEvents.ExecuteHierarchy(scrollHandler, scPointEventData, ExecuteEvents.scrollHandler);
  162. }
  163. scPointEventDataxx = scPointEventData;
  164. }
  165. private static bool ShouldStartDrag(Vector3 pressPos, Vector3 currentPos, float threshold, bool useDragThreshold, PointerEventData pointerEventData) {
  166. if (useDragThreshold) {
  167. if (!useDragThreshold)
  168. return true;
  169. return (pressPos - currentPos).magnitude >= threshold * 0.0005f;
  170. }
  171. return true;
  172. }
  173. protected override void ProcessDrag(PointerEventData pointerEvent) {
  174. if(!pointerEvent.IsPointerMoving() ||
  175. Cursor.lockState == CursorLockMode.Locked ||
  176. pointerEvent.pointerDrag == null)
  177. return;
  178. if(!pointerEvent.dragging
  179. && ShouldStartDrag((pointerEvent as SCPointEventData).PressPosition3D, (pointerEvent as SCPointEventData).Position3D, eventSystem.pixelDragThreshold, pointerEvent.useDragThreshold, pointerEvent)) {
  180. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.beginDragHandler);
  181. pointerEvent.dragging = true;
  182. }
  183. // Drag notification
  184. if(pointerEvent.dragging) {
  185. // Before doing drag we should cancel any pointer down state
  186. // And clear selection!
  187. //&& ((pointerEvent as SCPointEventData).downtimer >= (pointerEvent as SCPointEventData).TriggerDeltaTime) ? true : false 解决3D环境下误触发Drag导致后,松开不能正常触发click的问题
  188. if (pointerEvent.pointerPress != pointerEvent.pointerDrag && ((pointerEvent as SCPointEventData).downtimer >= (pointerEvent as SCPointEventData).TriggerDeltaTime) ? true : false) {
  189. ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
  190. pointerEvent.eligibleForClick = false;
  191. pointerEvent.pointerPress = null;
  192. pointerEvent.rawPointerPress = null;
  193. }
  194. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.dragHandler);
  195. }
  196. }
  197. protected PointerEventData.FramePressState StateForMouseButton(InputDevicePartBase devicePart) {
  198. var pressed = devicePart.inputDataBase.inputKeys.GetKeyDown(InputKeyCode.Enter);
  199. var released = devicePart.inputDataBase.inputKeys.GetKeyUp(InputKeyCode.Enter);
  200. if(pressed && released)
  201. return PointerEventData.FramePressState.PressedAndReleased;
  202. if(pressed)
  203. return PointerEventData.FramePressState.Pressed;
  204. if(released)
  205. return PointerEventData.FramePressState.Released;
  206. return PointerEventData.FramePressState.NotChanged;
  207. }
  208. protected PhysicsRaycaster EnsurePhysicsRaycaster() {
  209. mPhysicsRaycaster = GetComponent<PhysicsRaycaster>();
  210. if(mPhysicsRaycaster == null) {
  211. mPhysicsRaycaster = gameObject.AddComponent<PhysicsRaycaster>();
  212. }
  213. return mPhysicsRaycaster;
  214. }
  215. protected Camera EnsureUIEventCamera(float maxDetectDistance = 30) {
  216. mRayCasterCamera = GetComponent<Camera>();
  217. if(!mRayCasterCamera) {
  218. mRayCasterCamera = gameObject.AddComponent<Camera>();
  219. }
  220. mRayCasterCamera.enabled = false;
  221. mRayCasterCamera.nearClipPlane = 0;
  222. mRayCasterCamera.farClipPlane = maxDetectDistance;
  223. mRayCasterCamera.clearFlags = CameraClearFlags.Color;
  224. mRayCasterCamera.backgroundColor = Color.black;
  225. mRayCasterCamera.orthographic = true;
  226. mRayCasterCamera.allowHDR = false;
  227. mRayCasterCamera.allowMSAA = false;
  228. mRayCasterCamera.orthographicSize = 0.1f;
  229. mRayCasterCamera.aspect = 1f;
  230. return mRayCasterCamera;
  231. }
  232. SCPointEventData scPointEventDataxx;
  233. //void OnDrawGizmos() {
  234. // if(Application.isPlaying) {
  235. // // Now show the input position.
  236. // //Gizmos.color = Color.red;
  237. // //foreach(var item in cornerLocalPostion) {
  238. // // Gizmos.DrawSphere(item, 0.01f);
  239. // //}
  240. // //Gizmos.color = Color.yellow;
  241. // //foreach(var item in midPointLocalPostion) {
  242. // // Gizmos.DrawSphere(item, 0.01f);
  243. // //}
  244. // if(scPointEventDataxx != null && scPointEventDataxx.DownPressGameObject) {
  245. // Gizmos.color = Color.black;
  246. // Gizmos.DrawSphere(scPointEventDataxx.PressPosition3D, 0.01f);
  247. // //Gizmos.color = Color.red * 0.5f;
  248. // Gizmos.DrawSphere(scPointEventDataxx.Position3D, 0.01f);
  249. // //Gizmos.color = Color.yellow * 0.5f;
  250. // if(scPointEventDataxx.pointerDrag != null) {
  251. // Gizmos.DrawSphere(scPointEventDataxx.dragObjPosition, 0.04f);
  252. // //Gizmos.color = Color.blue * 0.8f;
  253. // Gizmos.DrawSphere(scPointEventDataxx.dragAnchorPosition3D, 0.02f);
  254. // }
  255. // }
  256. // //if(scPointEventDataxx.pointerDrag)
  257. // //Gizmos.DrawSphere(scPointEventDataxx.pointerDrag.transform.position, 0.01f);
  258. // }
  259. //}
  260. }
  261. }