Skip to content

Instantly share code, notes, and snippets.

@saccadic
Created October 24, 2019 04:33
Show Gist options
  • Save saccadic/9560bc39013ff837f5e53f9cb3038942 to your computer and use it in GitHub Desktop.
Save saccadic/9560bc39013ff837f5e53f9cb3038942 to your computer and use it in GitHub Desktop.
Vive trackerのサンプルコード
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class vive_tracker : MonoBehaviour
{
public GameObject[] targetObjs;
public ETrackedDeviceClass targetClass = ETrackedDeviceClass.GenericTracker;
public KeyCode resetDeviceIds = KeyCode.Tab;
CVRSystem _vrSystem;
List<int> _validDeviceIds = new List<int>();
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);
}
}
}
// Start is called before the first frame update
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();
}
}
// Update is called once per frame
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