Skip to content

Instantly share code, notes, and snippets.

@shop-0761
Last active January 26, 2019 00:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shop-0761/491c95974151d6be979844088d89bc45 to your computer and use it in GitHub Desktop.
HMDなしでViveTrackerを使うサンプル
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class SelfManagementOfTrackedDevices : MonoBehaviour
{
public GameObject[] targetObjs;
public ETrackedDeviceClass targetClass = ETrackedDeviceClass.GenericTracker;
public KeyCode resetDeviceIds = KeyCode.Tab;
CVRSystem _vrSystem;
List<int> _validDeviceIds = new List<int>();
void Start()
{
var error = EVRInitError.None;
_vrSystem = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Other);
if (error != EVRInitError.None) { Debug.LogWarning("Init error: " + error); }
else
{
Debug.Log("init done");
foreach (var item in targetObjs) { item.SetActive(false); }
SetDeviceIds();
}
}
void SetDeviceIds()
{
_validDeviceIds.Clear();
for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
{
var deviceClass = _vrSystem.GetTrackedDeviceClass(i);
if (deviceClass != ETrackedDeviceClass.Invalid && deviceClass == targetClass)
{
Debug.Log("OpenVR device at " + i + ": " + deviceClass);
_validDeviceIds.Add((int)i);
targetObjs[_validDeviceIds.Count - 1].SetActive(true);
}
}
}
void UpdateTrackedObj()
{
TrackedDevicePose_t[] allPoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount];
_vrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, allPoses);
for (int i = 0; i < _validDeviceIds.Count; i++)
{
if (i < targetObjs.Length)
{
var pose = allPoses[_validDeviceIds[i]];
var absTracking = pose.mDeviceToAbsoluteTracking;
var mat = new SteamVR_Utils.RigidTransform(absTracking);
targetObjs[i].transform.SetPositionAndRotation(mat.pos, mat.rot);
}
}
}
void Update()
{
UpdateTrackedObj();
if(Input.GetKeyDown(resetDeviceIds)){
SetDeviceIds();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment