SteamVR_TrackedObject.cs 2.6 KB

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