ControllerInputActionManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. using System.Collections.Generic;
  2. using Unity.XR.CoreUtils.Bindings;
  3. using UnityEngine.Events;
  4. using UnityEngine.InputSystem;
  5. using UnityEngine.Serialization;
  6. using UnityEngine.XR.Interaction.Toolkit.Attachment;
  7. using UnityEngine.XR.Interaction.Toolkit.Inputs.Readers;
  8. using UnityEngine.XR.Interaction.Toolkit.Interactors;
  9. using UnityEngine.XR.Interaction.Toolkit.UI;
  10. namespace UnityEngine.XR.Interaction.Toolkit.Samples.StarterAssets
  11. {
  12. /// <summary>
  13. /// Use this class to mediate the interactors for a controller under different interaction states
  14. /// and the input actions used by them.
  15. /// </summary>
  16. /// <remarks>
  17. /// If the teleport ray input is engaged, the Ray Interactor used for distant manipulation is disabled
  18. /// and the Ray Interactor used for teleportation is enabled. If the Ray Interactor is selecting and it
  19. /// is configured to allow for attach transform manipulation, all locomotion input actions are disabled
  20. /// (teleport ray, move, and turn controls) to prevent input collision with the manipulation inputs used
  21. /// by the ray interactor.
  22. /// <br />
  23. /// A typical hierarchy also includes an XR Interaction Group component to mediate between interactors.
  24. /// The interaction group ensures that the Direct and Ray Interactors cannot interact at the same time,
  25. /// with the Direct Interactor taking priority over the Ray Interactor.
  26. /// </remarks>
  27. [AddComponentMenu("XR/Controller Input Action Manager")]
  28. public class ControllerInputActionManager : MonoBehaviour
  29. {
  30. [Space]
  31. [Header("Interactors")]
  32. [SerializeField]
  33. [Tooltip("The interactor used for distant/ray manipulation. Use this or Near-Far Interactor, not both.")]
  34. XRRayInteractor m_RayInteractor;
  35. [SerializeField]
  36. [Tooltip("Near-Far Interactor used for distant/ray manipulation. Use this or Ray Interactor, not both.")]
  37. NearFarInteractor m_NearFarInteractor;
  38. [SerializeField]
  39. [Tooltip("The interactor used for teleportation.")]
  40. XRRayInteractor m_TeleportInteractor;
  41. [Space]
  42. [Header("Controller Actions")]
  43. [SerializeField]
  44. [Tooltip("The reference to the action to start the teleport aiming mode for this controller.")]
  45. [FormerlySerializedAs("m_TeleportModeActivate")]
  46. InputActionReference m_TeleportMode;
  47. [SerializeField]
  48. [Tooltip("The reference to the action to cancel the teleport aiming mode for this controller.")]
  49. InputActionReference m_TeleportModeCancel;
  50. [SerializeField]
  51. [Tooltip("The reference to the action of continuous turning the XR Origin with this controller.")]
  52. InputActionReference m_Turn;
  53. [SerializeField]
  54. [Tooltip("The reference to the action of snap turning the XR Origin with this controller.")]
  55. InputActionReference m_SnapTurn;
  56. [SerializeField]
  57. [Tooltip("The reference to the action of moving the XR Origin with this controller.")]
  58. InputActionReference m_Move;
  59. [SerializeField]
  60. [Tooltip("The reference to the action of scrolling UI with this controller.")]
  61. InputActionReference m_UIScroll;
  62. [Space]
  63. [Header("Locomotion Settings")]
  64. [SerializeField]
  65. [Tooltip("If true, continuous movement will be enabled. If false, teleport will be enabled.")]
  66. bool m_SmoothMotionEnabled;
  67. [SerializeField]
  68. [Tooltip("If true, continuous turn will be enabled. If false, snap turn will be enabled. Note: If smooth motion is enabled and enable strafe is enabled on the continuous move provider, turn will be overriden in favor of strafe.")]
  69. bool m_SmoothTurnEnabled;
  70. [SerializeField]
  71. [Tooltip("With the Near-Far Interactor, if true, teleport will be enabled during near interaction. If false, teleport will be disabled during near interaction.")]
  72. bool m_NearFarEnableTeleportDuringNearInteraction = true;
  73. [Space]
  74. [Header("UI Settings")]
  75. [SerializeField]
  76. [Tooltip("If true, UI scrolling will be enabled. Locomotion will be disabled when pointing at UI to allow it to be scrolled.")]
  77. bool m_UIScrollingEnabled = true;
  78. [Space]
  79. [Header("Mediation Events")]
  80. [SerializeField]
  81. [Tooltip("Event fired when the active ray interactor changes between interaction and teleport.")]
  82. UnityEvent<IXRRayProvider> m_RayInteractorChanged;
  83. public bool smoothMotionEnabled
  84. {
  85. get => m_SmoothMotionEnabled;
  86. set
  87. {
  88. m_SmoothMotionEnabled = value;
  89. UpdateLocomotionActions();
  90. }
  91. }
  92. public bool smoothTurnEnabled
  93. {
  94. get => m_SmoothTurnEnabled;
  95. set
  96. {
  97. m_SmoothTurnEnabled = value;
  98. UpdateLocomotionActions();
  99. }
  100. }
  101. public bool uiScrollingEnabled
  102. {
  103. get => m_UIScrollingEnabled;
  104. set
  105. {
  106. m_UIScrollingEnabled = value;
  107. UpdateUIActions();
  108. }
  109. }
  110. bool m_StartCalled;
  111. bool m_PostponedDeactivateTeleport;
  112. bool m_PostponedNearRegionLocomotion;
  113. bool m_HoveringScrollableUI;
  114. readonly HashSet<InputAction> m_LocomotionUsers = new HashSet<InputAction>();
  115. readonly BindingsGroup m_BindingsGroup = new BindingsGroup();
  116. void SetupInteractorEvents()
  117. {
  118. if (m_NearFarInteractor != null)
  119. {
  120. m_NearFarInteractor.uiHoverEntered.AddListener(OnUIHoverEntered);
  121. m_NearFarInteractor.uiHoverExited.AddListener(OnUIHoverExited);
  122. m_BindingsGroup.AddBinding(m_NearFarInteractor.selectionRegion.Subscribe(OnNearFarSelectionRegionChanged));
  123. }
  124. if (m_RayInteractor != null)
  125. {
  126. m_RayInteractor.selectEntered.AddListener(OnRaySelectEntered);
  127. m_RayInteractor.selectExited.AddListener(OnRaySelectExited);
  128. m_RayInteractor.uiHoverEntered.AddListener(OnUIHoverEntered);
  129. m_RayInteractor.uiHoverExited.AddListener(OnUIHoverExited);
  130. }
  131. var teleportModeAction = GetInputAction(m_TeleportMode);
  132. if (teleportModeAction != null)
  133. {
  134. teleportModeAction.performed += OnStartTeleport;
  135. teleportModeAction.performed += OnStartLocomotion;
  136. teleportModeAction.canceled += OnCancelTeleport;
  137. teleportModeAction.canceled += OnStopLocomotion;
  138. }
  139. var teleportModeCancelAction = GetInputAction(m_TeleportModeCancel);
  140. if (teleportModeCancelAction != null)
  141. {
  142. teleportModeCancelAction.performed += OnCancelTeleport;
  143. }
  144. var moveAction = GetInputAction(m_Move);
  145. if (moveAction != null)
  146. {
  147. moveAction.started += OnStartLocomotion;
  148. moveAction.canceled += OnStopLocomotion;
  149. }
  150. var turnAction = GetInputAction(m_Turn);
  151. if (turnAction != null)
  152. {
  153. turnAction.started += OnStartLocomotion;
  154. turnAction.canceled += OnStopLocomotion;
  155. }
  156. var snapTurnAction = GetInputAction(m_SnapTurn);
  157. if (snapTurnAction != null)
  158. {
  159. snapTurnAction.started += OnStartLocomotion;
  160. snapTurnAction.canceled += OnStopLocomotion;
  161. }
  162. }
  163. void TeardownInteractorEvents()
  164. {
  165. m_BindingsGroup.Clear();
  166. if (m_NearFarInteractor != null)
  167. {
  168. m_NearFarInteractor.uiHoverEntered.RemoveListener(OnUIHoverEntered);
  169. m_NearFarInteractor.uiHoverExited.RemoveListener(OnUIHoverExited);
  170. }
  171. if (m_RayInteractor != null)
  172. {
  173. m_RayInteractor.selectEntered.RemoveListener(OnRaySelectEntered);
  174. m_RayInteractor.selectExited.RemoveListener(OnRaySelectExited);
  175. m_RayInteractor.uiHoverEntered.RemoveListener(OnUIHoverEntered);
  176. m_RayInteractor.uiHoverExited.RemoveListener(OnUIHoverExited);
  177. }
  178. var teleportModeAction = GetInputAction(m_TeleportMode);
  179. if (teleportModeAction != null)
  180. {
  181. teleportModeAction.performed -= OnStartTeleport;
  182. teleportModeAction.performed -= OnStartLocomotion;
  183. teleportModeAction.canceled -= OnCancelTeleport;
  184. teleportModeAction.canceled -= OnStopLocomotion;
  185. }
  186. var teleportModeCancelAction = GetInputAction(m_TeleportModeCancel);
  187. if (teleportModeCancelAction != null)
  188. {
  189. teleportModeCancelAction.performed -= OnCancelTeleport;
  190. }
  191. var moveAction = GetInputAction(m_Move);
  192. if (moveAction != null)
  193. {
  194. moveAction.started -= OnStartLocomotion;
  195. moveAction.canceled -= OnStopLocomotion;
  196. }
  197. var turnAction = GetInputAction(m_Turn);
  198. if (turnAction != null)
  199. {
  200. turnAction.started -= OnStartLocomotion;
  201. turnAction.canceled -= OnStopLocomotion;
  202. }
  203. var snapTurnAction = GetInputAction(m_SnapTurn);
  204. if (snapTurnAction != null)
  205. {
  206. snapTurnAction.started -= OnStartLocomotion;
  207. snapTurnAction.canceled -= OnStopLocomotion;
  208. }
  209. }
  210. void OnStartTeleport(InputAction.CallbackContext context)
  211. {
  212. m_PostponedDeactivateTeleport = false;
  213. if (m_TeleportInteractor != null)
  214. m_TeleportInteractor.gameObject.SetActive(true);
  215. if (m_RayInteractor != null)
  216. m_RayInteractor.gameObject.SetActive(false);
  217. if (m_NearFarInteractor != null && m_NearFarInteractor.selectionRegion.Value != NearFarInteractor.Region.Near)
  218. m_NearFarInteractor.gameObject.SetActive(false);
  219. m_RayInteractorChanged?.Invoke(m_TeleportInteractor);
  220. }
  221. void OnCancelTeleport(InputAction.CallbackContext context)
  222. {
  223. // Do not deactivate the teleport interactor in this callback.
  224. // We delay turning off the teleport interactor in this callback so that
  225. // the teleport interactor has a chance to complete the teleport if needed.
  226. // OnAfterInteractionEvents will handle deactivating its GameObject.
  227. m_PostponedDeactivateTeleport = true;
  228. if (m_RayInteractor != null)
  229. m_RayInteractor.gameObject.SetActive(true);
  230. if (m_NearFarInteractor != null)
  231. m_NearFarInteractor.gameObject.SetActive(true);
  232. m_RayInteractorChanged?.Invoke(m_RayInteractor);
  233. }
  234. void OnStartLocomotion(InputAction.CallbackContext context)
  235. {
  236. m_LocomotionUsers.Add(context.action);
  237. }
  238. void OnStopLocomotion(InputAction.CallbackContext context)
  239. {
  240. m_LocomotionUsers.Remove(context.action);
  241. if (m_LocomotionUsers.Count == 0 && m_HoveringScrollableUI)
  242. {
  243. DisableAllLocomotionActions();
  244. UpdateUIActions();
  245. }
  246. }
  247. void OnNearFarSelectionRegionChanged(NearFarInteractor.Region selectionRegion)
  248. {
  249. m_PostponedNearRegionLocomotion = false;
  250. if (selectionRegion == NearFarInteractor.Region.None)
  251. {
  252. UpdateLocomotionActions();
  253. return;
  254. }
  255. var manipulateAttachTransform = false;
  256. var attachController = m_NearFarInteractor.interactionAttachController as InteractionAttachController;
  257. if (attachController != null)
  258. {
  259. manipulateAttachTransform = attachController.useManipulationInput &&
  260. (attachController.manipulationInput.inputSourceMode == XRInputValueReader.InputSourceMode.InputActionReference && attachController.manipulationInput.inputActionReference != null) ||
  261. (attachController.manipulationInput.inputSourceMode != XRInputValueReader.InputSourceMode.InputActionReference && attachController.manipulationInput.inputSourceMode != XRInputValueReader.InputSourceMode.Unused);
  262. }
  263. if (selectionRegion == NearFarInteractor.Region.Far)
  264. {
  265. if (manipulateAttachTransform)
  266. DisableAllLocomotionActions();
  267. else
  268. DisableTeleportActions();
  269. }
  270. else if (selectionRegion == NearFarInteractor.Region.Near)
  271. {
  272. // Determine if the user entered the near region due to pulling back on the thumbstick.
  273. // If so, postpone enabling locomotion until the user releases the thumbstick
  274. // in order to avoid an immediate snap turn around from triggering on region change.
  275. var hasStickInput = manipulateAttachTransform && HasStickInput(attachController);
  276. if (hasStickInput)
  277. {
  278. m_PostponedNearRegionLocomotion = true;
  279. DisableAllLocomotionActions();
  280. }
  281. else
  282. {
  283. UpdateLocomotionActions();
  284. if (!m_NearFarEnableTeleportDuringNearInteraction)
  285. DisableTeleportActions();
  286. }
  287. }
  288. }
  289. void OnRaySelectEntered(SelectEnterEventArgs args)
  290. {
  291. if (m_RayInteractor.manipulateAttachTransform)
  292. {
  293. // Disable locomotion and turn actions
  294. DisableAllLocomotionActions();
  295. }
  296. }
  297. void OnRaySelectExited(SelectExitEventArgs args)
  298. {
  299. if (m_RayInteractor.manipulateAttachTransform)
  300. {
  301. // Re-enable the locomotion and turn actions
  302. UpdateLocomotionActions();
  303. }
  304. }
  305. void OnUIHoverEntered(UIHoverEventArgs args)
  306. {
  307. m_HoveringScrollableUI = m_UIScrollingEnabled && args.deviceModel.isScrollable;
  308. UpdateUIActions();
  309. // If locomotion is occurring, wait
  310. if (m_HoveringScrollableUI && m_LocomotionUsers.Count == 0)
  311. {
  312. // Disable locomotion and turn actions
  313. DisableAllLocomotionActions();
  314. }
  315. }
  316. void OnUIHoverExited(UIHoverEventArgs args)
  317. {
  318. m_HoveringScrollableUI = false;
  319. UpdateUIActions();
  320. // Re-enable the locomotion and turn actions
  321. UpdateLocomotionActions();
  322. }
  323. protected void OnEnable()
  324. {
  325. if (m_RayInteractor != null && m_NearFarInteractor != null)
  326. {
  327. Debug.LogWarning("Both Ray Interactor and Near-Far Interactor are assigned. Only one should be assigned, not both. Clearing Ray Interactor.", this);
  328. m_RayInteractor = null;
  329. }
  330. if (m_TeleportInteractor != null)
  331. m_TeleportInteractor.gameObject.SetActive(false);
  332. // Allow the actions to be refreshed when this component is re-enabled.
  333. // See comments in Start for why we wait until Start to enable/disable actions.
  334. if (m_StartCalled)
  335. {
  336. UpdateLocomotionActions();
  337. UpdateUIActions();
  338. }
  339. SetupInteractorEvents();
  340. }
  341. protected void OnDisable()
  342. {
  343. TeardownInteractorEvents();
  344. }
  345. protected void Start()
  346. {
  347. m_StartCalled = true;
  348. // Ensure the enabled state of locomotion and turn actions are properly set up.
  349. // Called in Start so it is done after the InputActionManager enables all input actions earlier in OnEnable.
  350. UpdateLocomotionActions();
  351. UpdateUIActions();
  352. }
  353. protected void Update()
  354. {
  355. // Since this behavior has the default execution order, it runs after the XRInteractionManager,
  356. // so selection events have been finished by now this frame. This means that the teleport interactor
  357. // has had a chance to process its select interaction event and teleport if needed.
  358. if (m_PostponedDeactivateTeleport)
  359. {
  360. if (m_TeleportInteractor != null)
  361. m_TeleportInteractor.gameObject.SetActive(false);
  362. m_PostponedDeactivateTeleport = false;
  363. }
  364. // If stick input caused the near region to be entered,
  365. // wait until the stick is released before enabling locomotion.
  366. if (m_PostponedNearRegionLocomotion)
  367. {
  368. var hasStickInput = false;
  369. if (m_NearFarInteractor != null &&
  370. m_NearFarInteractor.interactionAttachController is InteractionAttachController attachController
  371. && attachController != null)
  372. {
  373. hasStickInput = HasStickInput(attachController);
  374. }
  375. if (!hasStickInput)
  376. {
  377. m_PostponedNearRegionLocomotion = false;
  378. UpdateLocomotionActions();
  379. if (!m_NearFarEnableTeleportDuringNearInteraction)
  380. DisableTeleportActions();
  381. }
  382. }
  383. }
  384. void UpdateLocomotionActions()
  385. {
  386. // Disable/enable Teleport and Turn when Move is enabled/disabled.
  387. SetEnabled(m_Move, m_SmoothMotionEnabled);
  388. SetEnabled(m_TeleportMode, !m_SmoothMotionEnabled);
  389. SetEnabled(m_TeleportModeCancel, !m_SmoothMotionEnabled);
  390. // Disable ability to turn when using continuous movement
  391. SetEnabled(m_Turn, !m_SmoothMotionEnabled && m_SmoothTurnEnabled);
  392. SetEnabled(m_SnapTurn, !m_SmoothMotionEnabled && !m_SmoothTurnEnabled);
  393. }
  394. void DisableTeleportActions()
  395. {
  396. DisableAction(m_TeleportMode);
  397. DisableAction(m_TeleportModeCancel);
  398. }
  399. void DisableMoveAndTurnActions()
  400. {
  401. DisableAction(m_Move);
  402. DisableAction(m_Turn);
  403. DisableAction(m_SnapTurn);
  404. }
  405. void DisableAllLocomotionActions()
  406. {
  407. DisableTeleportActions();
  408. DisableMoveAndTurnActions();
  409. }
  410. void UpdateUIActions()
  411. {
  412. SetEnabled(m_UIScroll, m_UIScrollingEnabled && m_HoveringScrollableUI && m_LocomotionUsers.Count == 0);
  413. }
  414. static bool HasStickInput(InteractionAttachController attachController)
  415. {
  416. // 75% of default 0.5 press threshold
  417. const float sqrStickReleaseThreshold = 0.375f * 0.375f;
  418. return attachController.manipulationInput.TryReadValue(out var stickInput) &&
  419. stickInput.sqrMagnitude > sqrStickReleaseThreshold;
  420. }
  421. static void SetEnabled(InputActionReference actionReference, bool enabled)
  422. {
  423. if (enabled)
  424. EnableAction(actionReference);
  425. else
  426. DisableAction(actionReference);
  427. }
  428. static void EnableAction(InputActionReference actionReference)
  429. {
  430. var action = GetInputAction(actionReference);
  431. action?.Enable();
  432. }
  433. static void DisableAction(InputActionReference actionReference)
  434. {
  435. var action = GetInputAction(actionReference);
  436. action?.Disable();
  437. }
  438. static InputAction GetInputAction(InputActionReference actionReference)
  439. {
  440. #pragma warning disable IDE0031 // Use null propagation -- Do not use for UnityEngine.Object types
  441. return actionReference != null ? actionReference.action : null;
  442. #pragma warning restore IDE0031
  443. }
  444. }
  445. }