SCInputModule.cs 15 KB

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