SteamVR_TrackedObject.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. }
  32. public EIndex index;
  33. [Tooltip("If not set, relative to parent")]
  34. public Transform origin;
  35. public bool isValid { get; private set; }
  36. private void OnNewPoses(TrackedDevicePose_t[] poses)
  37. {
  38. if (index == EIndex.None)
  39. return;
  40. var i = (int)index;
  41. isValid = false;
  42. if (poses.Length <= i)
  43. return;
  44. if (!poses[i].bDeviceIsConnected)
  45. return;
  46. if (!poses[i].bPoseIsValid)
  47. return;
  48. isValid = true;
  49. var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);
  50. if (origin != null)
  51. {
  52. transform.position = origin.transform.TransformPoint(pose.pos);
  53. transform.rotation = origin.rotation * pose.rot;
  54. }
  55. else
  56. {
  57. transform.localPosition = pose.pos;
  58. transform.localRotation = pose.rot;
  59. }
  60. }
  61. SteamVR_Events.Action newPosesAction;
  62. SteamVR_TrackedObject()
  63. {
  64. newPosesAction = SteamVR_Events.NewPosesAction(OnNewPoses);
  65. }
  66. private void Awake()
  67. {
  68. OnEnable();
  69. }
  70. void OnEnable()
  71. {
  72. var render = SteamVR_Render.instance;
  73. if (render == null)
  74. {
  75. enabled = false;
  76. return;
  77. }
  78. newPosesAction.enabled = true;
  79. }
  80. void OnDisable()
  81. {
  82. newPosesAction.enabled = false;
  83. isValid = false;
  84. }
  85. public void SetDeviceIndex(int index)
  86. {
  87. if (System.Enum.IsDefined(typeof(EIndex), index))
  88. this.index = (EIndex)index;
  89. }
  90. }
  91. }