IMHOTEP Framework
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Pages
SteamVR_TrackedObject.cs
1 //======= Copyright (c) Valve Corporation, All rights reserved. ===============
2 //
3 // Purpose: For controlling in-game objects with tracked devices.
4 //
5 //=============================================================================
6 
7 using UnityEngine;
8 using 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 
33  public EIndex index;
34 
35  [Tooltip("If not set, relative to parent")]
36  public Transform origin;
37 
38  public bool isValid { get; private set; }
39 
40  private void OnNewPoses(TrackedDevicePose_t[] poses)
41  {
42  if (index == EIndex.None)
43  return;
44 
45  var i = (int)index;
46 
47  isValid = false;
48  if (poses.Length <= i)
49  return;
50 
51  if (!poses[i].bDeviceIsConnected)
52  return;
53 
54  if (!poses[i].bPoseIsValid)
55  return;
56 
57  isValid = true;
58 
59  var pose = new SteamVR_Utils.RigidTransform(poses[i].mDeviceToAbsoluteTracking);
60 
61  if (origin != null)
62  {
63  transform.position = origin.transform.TransformPoint(pose.pos);
64  transform.rotation = origin.rotation * pose.rot;
65  }
66  else
67  {
68  transform.localPosition = pose.pos;
69  transform.localRotation = pose.rot;
70  }
71  }
72 
73  SteamVR_Events.Action newPosesAction;
74 
76  {
77  newPosesAction = SteamVR_Events.NewPosesAction(OnNewPoses);
78  }
79 
80  void OnEnable()
81  {
82  var render = SteamVR_Render.instance;
83  if (render == null)
84  {
85  enabled = false;
86  return;
87  }
88 
89  newPosesAction.enabled = true;
90  }
91 
92  void OnDisable()
93  {
94  newPosesAction.enabled = false;
95  isValid = false;
96  }
97 
98  public void SetDeviceIndex(int index)
99  {
100  if (System.Enum.IsDefined(typeof(EIndex), index))
101  this.index = (EIndex)index;
102  }
103 }
104