Skip to content

Instantly share code, notes, and snippets.

@gtk2k
Created February 25, 2020 04:54
Show Gist options
  • Select an option

  • Save gtk2k/8dad9812ac82680831c4c73e48210548 to your computer and use it in GitHub Desktop.

Select an option

Save gtk2k/8dad9812ac82680831c4c73e48210548 to your computer and use it in GitHub Desktop.
GetUnityXRInputDevice.cs
public class XRTracker : MonoBehaviour
{
//Keep this around to avoid creating heap garbage
static List<InputDevice> devices = new List<InputDevice>();
[SerializeField]
InputDeviceRole role;
InputDevice trackedDevice;
void OnEnable()
{
InputDevices.deviceConnected += OnDeviceConnected;
InputDevices.deviceConnected += OnDeviceDisconnected;
Application.onBeforeRender += OnBeforeRender;
InputDevices.GetDevicesWithRole(role, devices);
if (devices.Count > 0)
OnDeviceConnected(devices[0]);
}
void OnDisable()
{
InputDevices.deviceConnected -= OnDeviceConnected;
InputDevices.deviceConnected -= OnDeviceDisconnected;
Application.onBeforeRender -= OnBeforeRender;
}
void Update()
{
if (trackedDevice.isValid)
TrackToDevice(trackedDevice);
}
void OnDeviceConnected(InputDevice device)
{
if (!trackedDevice.isValid && device.role == role)
trackedDevice = device;
}
void OnDeviceDisconnected(InputDevice device)
{
if (device == trackedDevice)
trackedDevice = new InputDevice();
}
void OnBeforeRender()
{
if (trackedDevice.isValid)
TrackToDevice(trackedDevice);
}
void TrackToDevice(InputDevice trackedDevice)
{
Vector3 position;
if (trackedDevice.TryGetFeatureValue(CommonUsages.devicePosition, out position))
this.transform.position = position;
Quaternion rotation;
if (trackedDevice.TryGetFeatureValue(CommonUsages.deviceRotation, out rotation))
this.transform.rotation = rotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment