Created
February 25, 2020 04:54
-
-
Save gtk2k/8dad9812ac82680831c4c73e48210548 to your computer and use it in GitHub Desktop.
GetUnityXRInputDevice.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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