Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
1.8 KiB

  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: For controlling in-game objects with tracked devices.
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using Valve.VR;
  8. public class SteamVR_TrackedObject : MonoBehaviour
  9. {
  10. public enum EIndex
  11. {
  12. None = -1,
  13. Hmd = (int)OpenVR.k_unTrackedDeviceIndex_Hmd,
  14. Device1,
  15. Device2,
  16. Device3,
  17. Device4,
  18. Device5,
  19. Device6,
  20. Device7,
  21. Device8,
  22. Device9,
  23. Device10,
  24. Device11,
  25. Device12,
  26. Device13,
  27. Device14,
  28. Device15
  29. }
  30. public EIndex index;
  31. [Tooltip("If not set, relative to parent")]
  32. public Transform origin;
  33. public bool isValid { get; private set; }
  34. private void OnNewPoses(TrackedDevicePose_t[] poses)
  35. {
  36. if (index == EIndex.None)
  37. return;
  38. var i = (int)index;
  39. isValid = false;
  40. if (poses.Length <= i)
  41. return;
  42. if (!poses[i].bDeviceIsConnected)
  43. return;
  44. if (!poses[i].bPoseIsValid)
  45. return;
  46. isValid = true;
  47. var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);
  48. if (origin != null)
  49. {
  50. transform.position = origin.transform.TransformPoint(pose.pos);
  51. transform.rotation = origin.rotation * pose.rot;
  52. }
  53. else
  54. {
  55. transform.localPosition = pose.pos;
  56. transform.localRotation = pose.rot;
  57. }
  58. }
  59. SteamVR_Events.Action newPosesAction;
  60. SteamVR_TrackedObject()
  61. {
  62. newPosesAction = SteamVR_Events.NewPosesAction(OnNewPoses);
  63. }
  64. void OnEnable()
  65. {
  66. var render = SteamVR_Render.instance;
  67. if (render == null)
  68. {
  69. enabled = false;
  70. return;
  71. }
  72. newPosesAction.enabled = true;
  73. }
  74. void OnDisable()
  75. {
  76. newPosesAction.enabled = false;
  77. isValid = false;
  78. }
  79. public void SetDeviceIndex(int index)
  80. {
  81. if (System.Enum.IsDefined(typeof(EIndex), index))
  82. this.index = (EIndex)index;
  83. }
  84. }