NRGrabber.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System;
  12. using System.Collections.Generic;
  13. using UnityEngine;
  14. /// <summary> A nr grabber. </summary>
  15. [RequireComponent(typeof(Rigidbody))]
  16. public class NRGrabber : MonoBehaviour
  17. {
  18. /// <summary> The grab button. </summary>
  19. public ControllerButton grabButton = ControllerButton.GRIP;
  20. /// <summary> The hand enum. </summary>
  21. public ControllerHandEnum handEnum;
  22. /// <summary> True to enable, false to disable the grab multi. </summary>
  23. public bool grabMultiEnabled = false;
  24. /// <summary> True to update pose by rigidbody. </summary>
  25. public bool updatePoseByRigidbody = true;
  26. /// <summary> True to previous grab press. </summary>
  27. private bool m_PreviousGrabPress;
  28. /// <summary> Dictionary of grab readies. </summary>
  29. private Dictionary<NRGrabbableObject, int> m_GrabReadyDict = new Dictionary<NRGrabbableObject, int>();
  30. /// <summary> Dictionary of grab start offset. </summary>
  31. private Dictionary<NRGrabbableObject, Pose> m_GrabStartOffsetDict = new Dictionary<NRGrabbableObject, Pose>();
  32. /// <summary> List of grabbings. </summary>
  33. private List<NRGrabbableObject> m_GrabbingList = new List<NRGrabbableObject>();
  34. /// <summary> The children colliders. </summary>
  35. private Collider[] m_ChildrenColliders;
  36. /// <summary> Func to judge if is grabbing. </summary>
  37. private Func<bool> m_FunToJudgeIsGrabbing;
  38. public bool IsGrabbingObjects{ get { return m_GrabbingList.Count > 0; } }
  39. /// <summary> Awakes this object. </summary>
  40. private void Awake()
  41. {
  42. Rigidbody rigid = GetComponent<Rigidbody>();
  43. rigid.useGravity = false;
  44. rigid.isKinematic = true;
  45. m_ChildrenColliders = GetComponentsInChildren<Collider>();
  46. }
  47. /// <summary> Executes the 'enable' action. </summary>
  48. private void OnEnable()
  49. {
  50. NRInput.OnControllerStatesUpdated += OnControllerPoseUpdated;
  51. }
  52. /// <summary> Executes the 'disable' action. </summary>
  53. private void OnDisable()
  54. {
  55. NRInput.OnControllerStatesUpdated -= OnControllerPoseUpdated;
  56. ReleaseAllGrabbedObject();
  57. }
  58. /// <summary> Fixed update. </summary>
  59. private void FixedUpdate()
  60. {
  61. if (!updatePoseByRigidbody)
  62. return;
  63. UpdateGrabbles();
  64. }
  65. /// <summary> Executes the 'trigger enter' action. </summary>
  66. /// <param name="other"> The other.</param>
  67. private void OnTriggerEnter(Collider other)
  68. {
  69. NRGrabbableObject grabble = other.GetComponent<NRGrabbableObject>() ?? other.GetComponentInParent<NRGrabbableObject>();
  70. if (grabble == null)
  71. return;
  72. if (m_GrabReadyDict.ContainsKey(grabble))
  73. {
  74. m_GrabReadyDict[grabble] += 1;
  75. }
  76. else
  77. {
  78. m_GrabReadyDict.Add(grabble, 1);
  79. }
  80. }
  81. /// <summary> Executes the 'trigger exit' action. </summary>
  82. /// <param name="other"> The other.</param>
  83. private void OnTriggerExit(Collider other)
  84. {
  85. NRGrabbableObject grabble = other.GetComponent<NRGrabbableObject>() ?? other.GetComponentInParent<NRGrabbableObject>();
  86. if (grabble == null)
  87. return;
  88. int count = 0;
  89. if (m_GrabReadyDict.TryGetValue(grabble, out count))
  90. {
  91. if (count > 1)
  92. {
  93. m_GrabReadyDict[grabble] = count - 1;
  94. }
  95. else
  96. {
  97. m_GrabReadyDict.Remove(grabble);
  98. }
  99. }
  100. }
  101. /// <summary> Executes the 'controller pose updated' action. </summary>
  102. private void OnControllerPoseUpdated()
  103. {
  104. if (updatePoseByRigidbody)
  105. return;
  106. UpdateGrabbles();
  107. }
  108. /// <summary> Updates the grabbles. </summary>
  109. private void UpdateGrabbles()
  110. {
  111. bool pressGrab = false;
  112. if (m_FunToJudgeIsGrabbing != null)
  113. {
  114. pressGrab = m_FunToJudgeIsGrabbing.Invoke();
  115. }
  116. else
  117. {
  118. pressGrab = NRInput.GetButton(handEnum, grabButton);
  119. }
  120. bool triggeredGrab = !m_PreviousGrabPress && pressGrab;
  121. bool releaseAction = m_PreviousGrabPress && !pressGrab;
  122. m_PreviousGrabPress = pressGrab;
  123. if (triggeredGrab && m_GrabbingList.Count == 0 && m_GrabReadyDict.Keys.Count != 0)
  124. {
  125. if (!grabMultiEnabled)
  126. {
  127. NRGrabbableObject nearestGrabble = GetNearestGrabbleObject();
  128. if (nearestGrabble)
  129. {
  130. GrabTarget(nearestGrabble);
  131. }
  132. }
  133. else
  134. {
  135. var grabbleQueue = new Queue<NRGrabbableObject>(m_GrabReadyDict.Keys);
  136. while(grabbleQueue.Count > 0)
  137. {
  138. GrabTarget(grabbleQueue.Dequeue());
  139. }
  140. m_GrabReadyDict.Clear();
  141. }
  142. SetChildrenCollidersEnabled(false);
  143. }
  144. if (releaseAction)
  145. {
  146. ReleaseAllGrabbedObject();
  147. return;
  148. }
  149. if (m_GrabbingList.Count > 0 && !triggeredGrab)
  150. {
  151. MoveGrabbingObjects();
  152. }
  153. }
  154. /// <summary> Gets nearest grabble object. </summary>
  155. /// <returns> The nearest grabble object. </returns>
  156. private NRGrabbableObject GetNearestGrabbleObject()
  157. {
  158. NRGrabbableObject nearestGrabble = null;
  159. float nearestSqrMagnitude = float.MaxValue;
  160. foreach (NRGrabbableObject grabbleObj in m_GrabReadyDict.Keys)
  161. {
  162. if (grabbleObj.AttachedColliders == null)
  163. continue;
  164. for (int i = 0; i < grabbleObj.AttachedColliders.Length; i++)
  165. {
  166. Vector3 closestPoint = grabbleObj.AttachedColliders[i].ClosestPointOnBounds(transform.position);
  167. float grabbableSqrMagnitude = (transform.position - closestPoint).sqrMagnitude;
  168. if (grabbableSqrMagnitude < nearestSqrMagnitude)
  169. {
  170. nearestSqrMagnitude = grabbableSqrMagnitude;
  171. nearestGrabble = grabbleObj;
  172. }
  173. }
  174. }
  175. return nearestGrabble;
  176. }
  177. /// <summary> Grab target. </summary>
  178. /// <param name="target"> Target for the.</param>
  179. private void GrabTarget(NRGrabbableObject target)
  180. {
  181. if (target == null || !target.CanGrab)
  182. return;
  183. if (!m_GrabbingList.Contains(target))
  184. {
  185. m_GrabbingList.Add(target);
  186. }
  187. if (!m_GrabStartOffsetDict.ContainsKey(target))
  188. {
  189. var offsetPosition = transform.InverseTransformPoint(target.transform.position);
  190. var offsetRotation = Quaternion.Inverse(transform.rotation) * target.transform.rotation;
  191. m_GrabStartOffsetDict.Add(target, new Pose(offsetPosition, offsetRotation));
  192. }
  193. m_GrabReadyDict.Remove(target);
  194. target.GrabBegin(this);
  195. }
  196. /// <summary> Move grabbing objects. </summary>
  197. private void MoveGrabbingObjects()
  198. {
  199. for (int i = 0; i < m_GrabbingList.Count; i++)
  200. {
  201. Vector3 targetPos;
  202. Quaternion targetRot;
  203. Pose offsetPose;
  204. if(m_GrabStartOffsetDict.TryGetValue(m_GrabbingList[i], out offsetPose))
  205. {
  206. targetPos = transform.TransformPoint(offsetPose.position);
  207. targetRot = transform.rotation * offsetPose.rotation;
  208. }
  209. else
  210. {
  211. targetPos = transform.position;
  212. targetRot = transform.rotation;
  213. }
  214. if (updatePoseByRigidbody)
  215. {
  216. m_GrabbingList[i].MoveRigidbody(targetPos, targetRot);
  217. }
  218. else
  219. {
  220. m_GrabbingList[i].MoveTransform(targetPos, targetRot);
  221. }
  222. }
  223. }
  224. /// <summary> Sets children colliders enabled. </summary>
  225. /// <param name="isEnabled"> True if is enabled, false if not.</param>
  226. private void SetChildrenCollidersEnabled(bool isEnabled)
  227. {
  228. if (m_ChildrenColliders == null)
  229. return;
  230. for (int i = 0; i < m_ChildrenColliders.Length; i++)
  231. {
  232. m_ChildrenColliders[i].enabled = isEnabled;
  233. }
  234. }
  235. /// <summary> Release all the grabbed objects. </summary>
  236. public void ReleaseAllGrabbedObject()
  237. {
  238. for (int i = 0; i < m_GrabbingList.Count; i++)
  239. {
  240. m_GrabbingList[i].GrabEnd();
  241. }
  242. m_GrabbingList.Clear();
  243. m_GrabStartOffsetDict.Clear();
  244. SetChildrenCollidersEnabled(true);
  245. }
  246. /// <summary> Set the condition to judge if is grabbing. </summary>
  247. /// <param name="judgeGrabbingFunc"></param>
  248. public void SetGrabJudgeCondition(Func<bool> judgeGrabbingFunc)
  249. {
  250. m_FunToJudgeIsGrabbing = judgeGrabbingFunc;
  251. }
  252. }
  253. }