OVRGrabber.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /************************************************************************************
  2. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  3. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
  4. the Utilities SDK except in compliance with the License, which is provided at the time of installation
  5. or download, or which otherwise accompanies this software in either electronic or hard copy form.
  6. You may obtain a copy of the License at
  7. https://developer.oculus.com/licenses/utilities-1.31
  8. Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
  9. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  10. ANY KIND, either express or implied. See the License for the specific language governing
  11. permissions and limitations under the License.
  12. ************************************************************************************/
  13. using System.Collections.Generic;
  14. using UnityEngine;
  15. /// <summary>
  16. /// Allows grabbing and throwing of objects with the OVRGrabbable component on them.
  17. /// </summary>
  18. [RequireComponent(typeof(Rigidbody))]
  19. public class OVRGrabber : MonoBehaviour
  20. {
  21. // Grip trigger thresholds for picking up objects, with some hysteresis.
  22. public float grabBegin = 0.55f;
  23. public float grabEnd = 0.35f;
  24. bool alreadyUpdated = false;
  25. // Demonstrates parenting the held object to the hand's transform when grabbed.
  26. // When false, the grabbed object is moved every FixedUpdate using MovePosition.
  27. // Note that MovePosition is required for proper physics simulation. If you set this to true, you can
  28. // easily observe broken physics simulation by, for example, moving the bottom cube of a stacked
  29. // tower and noting a complete loss of friction.
  30. [SerializeField]
  31. protected bool m_parentHeldObject = false;
  32. // If true, will move the hand to the transform specified by m_parentTransform, using MovePosition in
  33. // FixedUpdate. This allows correct physics behavior, at the cost of some latency.
  34. // (If false, the hand can simply be attached to the hand anchor, which updates position in LateUpdate,
  35. // gaining us a few ms of reduced latency.)
  36. [SerializeField]
  37. protected bool m_moveHandPosition = false;
  38. // Child/attached transforms of the grabber, indicating where to snap held objects to (if you snap them).
  39. // Also used for ranking grab targets in case of multiple candidates.
  40. [SerializeField]
  41. protected Transform m_gripTransform = null;
  42. // Child/attached Colliders to detect candidate grabbable objects.
  43. [SerializeField]
  44. protected Collider[] m_grabVolumes = null;
  45. // Should be OVRInput.Controller.LTouch or OVRInput.Controller.RTouch.
  46. [SerializeField]
  47. protected OVRInput.Controller m_controller;
  48. [SerializeField]
  49. protected Transform m_parentTransform;
  50. [SerializeField]
  51. protected GameObject m_player;
  52. protected bool m_grabVolumeEnabled = true;
  53. protected Vector3 m_lastPos;
  54. protected Quaternion m_lastRot;
  55. protected Quaternion m_anchorOffsetRotation;
  56. protected Vector3 m_anchorOffsetPosition;
  57. protected float m_prevFlex;
  58. protected OVRGrabbable m_grabbedObj = null;
  59. protected Vector3 m_grabbedObjectPosOff;
  60. protected Quaternion m_grabbedObjectRotOff;
  61. protected Dictionary<OVRGrabbable, int> m_grabCandidates = new Dictionary<OVRGrabbable, int>();
  62. protected bool m_operatingWithoutOVRCameraRig = true;
  63. /// <summary>
  64. /// The currently grabbed object.
  65. /// </summary>
  66. public OVRGrabbable grabbedObject
  67. {
  68. get { return m_grabbedObj; }
  69. }
  70. public void ForceRelease(OVRGrabbable grabbable)
  71. {
  72. bool canRelease = (
  73. (m_grabbedObj != null) &&
  74. (m_grabbedObj == grabbable)
  75. );
  76. if (canRelease)
  77. {
  78. GrabEnd();
  79. }
  80. }
  81. protected virtual void Awake()
  82. {
  83. m_anchorOffsetPosition = transform.localPosition;
  84. m_anchorOffsetRotation = transform.localRotation;
  85. if(!m_moveHandPosition)
  86. {
  87. // If we are being used with an OVRCameraRig, let it drive input updates, which may come from Update or FixedUpdate.
  88. OVRCameraRig rig = transform.GetComponentInParent<OVRCameraRig>();
  89. if (rig != null)
  90. {
  91. rig.UpdatedAnchors += (r) => {OnUpdatedAnchors();};
  92. m_operatingWithoutOVRCameraRig = false;
  93. }
  94. }
  95. }
  96. protected virtual void Start()
  97. {
  98. m_lastPos = transform.position;
  99. m_lastRot = transform.rotation;
  100. if(m_parentTransform == null)
  101. {
  102. if(gameObject.transform.parent != null)
  103. {
  104. m_parentTransform = gameObject.transform.parent.transform;
  105. }
  106. else
  107. {
  108. m_parentTransform = new GameObject().transform;
  109. m_parentTransform.position = Vector3.zero;
  110. m_parentTransform.rotation = Quaternion.identity;
  111. }
  112. }
  113. }
  114. virtual public void Update()
  115. {
  116. alreadyUpdated = false;
  117. }
  118. virtual public void FixedUpdate()
  119. {
  120. if (m_operatingWithoutOVRCameraRig)
  121. {
  122. OnUpdatedAnchors();
  123. }
  124. }
  125. // Hands follow the touch anchors by calling MovePosition each frame to reach the anchor.
  126. // This is done instead of parenting to achieve workable physics. If you don't require physics on
  127. // your hands or held objects, you may wish to switch to parenting.
  128. void OnUpdatedAnchors()
  129. {
  130. // Don't want to MovePosition multiple times in a frame, as it causes high judder in conjunction
  131. // with the hand position prediction in the runtime.
  132. if (alreadyUpdated) return;
  133. alreadyUpdated = true;
  134. Vector3 destPos = m_parentTransform.TransformPoint(m_anchorOffsetPosition);
  135. Quaternion destRot = m_parentTransform.rotation * m_anchorOffsetRotation;
  136. if (m_moveHandPosition)
  137. {
  138. GetComponent<Rigidbody>().MovePosition(destPos);
  139. GetComponent<Rigidbody>().MoveRotation(destRot);
  140. }
  141. if (!m_parentHeldObject)
  142. {
  143. MoveGrabbedObject(destPos, destRot);
  144. }
  145. m_lastPos = transform.position;
  146. m_lastRot = transform.rotation;
  147. float prevFlex = m_prevFlex;
  148. // Update values from inputs
  149. m_prevFlex = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, m_controller);
  150. CheckForGrabOrRelease(prevFlex);
  151. }
  152. void OnDestroy()
  153. {
  154. if (m_grabbedObj != null)
  155. {
  156. GrabEnd();
  157. }
  158. }
  159. void OnTriggerEnter(Collider otherCollider)
  160. {
  161. // Get the grab trigger
  162. OVRGrabbable grabbable = otherCollider.GetComponent<OVRGrabbable>() ?? otherCollider.GetComponentInParent<OVRGrabbable>();
  163. if (grabbable == null) return;
  164. // Add the grabbable
  165. int refCount = 0;
  166. m_grabCandidates.TryGetValue(grabbable, out refCount);
  167. m_grabCandidates[grabbable] = refCount + 1;
  168. }
  169. void OnTriggerExit(Collider otherCollider)
  170. {
  171. OVRGrabbable grabbable = otherCollider.GetComponent<OVRGrabbable>() ?? otherCollider.GetComponentInParent<OVRGrabbable>();
  172. if (grabbable == null) return;
  173. // Remove the grabbable
  174. int refCount = 0;
  175. bool found = m_grabCandidates.TryGetValue(grabbable, out refCount);
  176. if (!found)
  177. {
  178. return;
  179. }
  180. if (refCount > 1)
  181. {
  182. m_grabCandidates[grabbable] = refCount - 1;
  183. }
  184. else
  185. {
  186. m_grabCandidates.Remove(grabbable);
  187. }
  188. }
  189. protected void CheckForGrabOrRelease(float prevFlex)
  190. {
  191. if ((m_prevFlex >= grabBegin) && (prevFlex < grabBegin))
  192. {
  193. GrabBegin();
  194. }
  195. else if ((m_prevFlex <= grabEnd) && (prevFlex > grabEnd))
  196. {
  197. GrabEnd();
  198. }
  199. }
  200. protected virtual void GrabBegin()
  201. {
  202. float closestMagSq = float.MaxValue;
  203. OVRGrabbable closestGrabbable = null;
  204. Collider closestGrabbableCollider = null;
  205. // Iterate grab candidates and find the closest grabbable candidate
  206. foreach (OVRGrabbable grabbable in m_grabCandidates.Keys)
  207. {
  208. bool canGrab = !(grabbable.isGrabbed && !grabbable.allowOffhandGrab);
  209. if (!canGrab)
  210. {
  211. continue;
  212. }
  213. for (int j = 0; j < grabbable.grabPoints.Length; ++j)
  214. {
  215. Collider grabbableCollider = grabbable.grabPoints[j];
  216. // Store the closest grabbable
  217. Vector3 closestPointOnBounds = grabbableCollider.ClosestPointOnBounds(m_gripTransform.position);
  218. float grabbableMagSq = (m_gripTransform.position - closestPointOnBounds).sqrMagnitude;
  219. if (grabbableMagSq < closestMagSq)
  220. {
  221. closestMagSq = grabbableMagSq;
  222. closestGrabbable = grabbable;
  223. closestGrabbableCollider = grabbableCollider;
  224. }
  225. }
  226. }
  227. // Disable grab volumes to prevent overlaps
  228. GrabVolumeEnable(false);
  229. if (closestGrabbable != null)
  230. {
  231. if (closestGrabbable.isGrabbed)
  232. {
  233. closestGrabbable.grabbedBy.OffhandGrabbed(closestGrabbable);
  234. }
  235. m_grabbedObj = closestGrabbable;
  236. m_grabbedObj.GrabBegin(this, closestGrabbableCollider);
  237. m_lastPos = transform.position;
  238. m_lastRot = transform.rotation;
  239. // Set up offsets for grabbed object desired position relative to hand.
  240. if(m_grabbedObj.snapPosition)
  241. {
  242. m_grabbedObjectPosOff = m_gripTransform.localPosition;
  243. if(m_grabbedObj.snapOffset)
  244. {
  245. Vector3 snapOffset = m_grabbedObj.snapOffset.position;
  246. if (m_controller == OVRInput.Controller.LTouch) snapOffset.x = -snapOffset.x;
  247. m_grabbedObjectPosOff += snapOffset;
  248. }
  249. }
  250. else
  251. {
  252. Vector3 relPos = m_grabbedObj.transform.position - transform.position;
  253. relPos = Quaternion.Inverse(transform.rotation) * relPos;
  254. m_grabbedObjectPosOff = relPos;
  255. }
  256. if (m_grabbedObj.snapOrientation)
  257. {
  258. m_grabbedObjectRotOff = m_gripTransform.localRotation;
  259. if(m_grabbedObj.snapOffset)
  260. {
  261. m_grabbedObjectRotOff = m_grabbedObj.snapOffset.rotation * m_grabbedObjectRotOff;
  262. }
  263. }
  264. else
  265. {
  266. Quaternion relOri = Quaternion.Inverse(transform.rotation) * m_grabbedObj.transform.rotation;
  267. m_grabbedObjectRotOff = relOri;
  268. }
  269. // Note: force teleport on grab, to avoid high-speed travel to dest which hits a lot of other objects at high
  270. // speed and sends them flying. The grabbed object may still teleport inside of other objects, but fixing that
  271. // is beyond the scope of this demo.
  272. MoveGrabbedObject(m_lastPos, m_lastRot, true);
  273. SetPlayerIgnoreCollision(m_grabbedObj.gameObject, true);
  274. if (m_parentHeldObject)
  275. {
  276. m_grabbedObj.transform.parent = transform;
  277. }
  278. }
  279. }
  280. protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
  281. {
  282. if (m_grabbedObj == null)
  283. {
  284. return;
  285. }
  286. Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
  287. Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
  288. Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;
  289. if (forceTeleport)
  290. {
  291. grabbedRigidbody.transform.position = grabbablePosition;
  292. grabbedRigidbody.transform.rotation = grabbableRotation;
  293. }
  294. else
  295. {
  296. grabbedRigidbody.MovePosition(grabbablePosition);
  297. grabbedRigidbody.MoveRotation(grabbableRotation);
  298. }
  299. }
  300. protected void GrabEnd()
  301. {
  302. if (m_grabbedObj != null)
  303. {
  304. OVRPose localPose = new OVRPose { position = OVRInput.GetLocalControllerPosition(m_controller), orientation = OVRInput.GetLocalControllerRotation(m_controller) };
  305. OVRPose offsetPose = new OVRPose { position = m_anchorOffsetPosition, orientation = m_anchorOffsetRotation };
  306. localPose = localPose * offsetPose;
  307. OVRPose trackingSpace = transform.ToOVRPose() * localPose.Inverse();
  308. Vector3 linearVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerVelocity(m_controller);
  309. Vector3 angularVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerAngularVelocity(m_controller);
  310. GrabbableRelease(linearVelocity, angularVelocity);
  311. }
  312. // Re-enable grab volumes to allow overlap events
  313. GrabVolumeEnable(true);
  314. }
  315. protected void GrabbableRelease(Vector3 linearVelocity, Vector3 angularVelocity)
  316. {
  317. m_grabbedObj.GrabEnd(linearVelocity, angularVelocity);
  318. if(m_parentHeldObject) m_grabbedObj.transform.parent = null;
  319. SetPlayerIgnoreCollision(m_grabbedObj.gameObject, false);
  320. m_grabbedObj = null;
  321. }
  322. protected virtual void GrabVolumeEnable(bool enabled)
  323. {
  324. if (m_grabVolumeEnabled == enabled)
  325. {
  326. return;
  327. }
  328. m_grabVolumeEnabled = enabled;
  329. for (int i = 0; i < m_grabVolumes.Length; ++i)
  330. {
  331. Collider grabVolume = m_grabVolumes[i];
  332. grabVolume.enabled = m_grabVolumeEnabled;
  333. }
  334. if (!m_grabVolumeEnabled)
  335. {
  336. m_grabCandidates.Clear();
  337. }
  338. }
  339. protected virtual void OffhandGrabbed(OVRGrabbable grabbable)
  340. {
  341. if (m_grabbedObj == grabbable)
  342. {
  343. GrabbableRelease(Vector3.zero, Vector3.zero);
  344. }
  345. }
  346. protected void SetPlayerIgnoreCollision(GameObject grabbable, bool ignore)
  347. {
  348. if (m_player != null)
  349. {
  350. Collider playerCollider = m_player.GetComponent<Collider>();
  351. if (playerCollider != null)
  352. {
  353. Collider[] colliders = grabbable.GetComponents<Collider>();
  354. foreach (Collider c in colliders)
  355. {
  356. Physics.IgnoreCollision(c, playerCollider, ignore);
  357. }
  358. }
  359. }
  360. }
  361. }