Skip to content

Instantly share code, notes, and snippets.

@Feddas
Last active March 23, 2018 02:40
Show Gist options
  • Save Feddas/b24ae20202c963150e882eaaebe988c6 to your computer and use it in GitHub Desktop.
Save Feddas/b24ae20202c963150e882eaaebe988c6 to your computer and use it in GitHub Desktop.
Get the tracking spaces origin position and rotation
using UnityEngine;
using UnityEngine.VR;
public class AlignToVrNode : MonoBehaviour
{
public VRNode VrNode = VRNode.RightHand;
void Awake()
{
//If VR isn't enabled, don't try to track this object
if (VRSettings.enabled == false)
Destroy(this);
VrOrigin.SetVrHead(Camera.main.transform);
}
private void Update()
{
this.transform.position = VrOrigin.Position + UnityEngine.VR.InputTracking.GetLocalPosition(VrNode);
this.transform.rotation = VrOrigin.Rotation * UnityEngine.VR.InputTracking.GetLocalRotation(VrNode);
}
}
using UnityEngine;
/// <summary>
/// Determines the position and rotation of the VR spaces origin.
/// Works Best if VrOrigin.SetVrHead(Camera.main.transform); is called from Awake()
/// </summary>
public static class VrOrigin
{
public static Vector3 Position
{
get
{
if (vrHead.parent == null)
{
return startLocalPosition;
}
else
{
updateOrigin();
return _position;
}
}
}
private static Vector3 _position;
public static Quaternion Rotation
{
get
{
if (vrHead.parent == null)
{
return startLocalRotation;
}
else
{
updateOrigin();
return _rotation;
}
}
}
private static Quaternion _rotation;
private static Vector3 startLocalPosition;
private static Quaternion startLocalRotation;
private static Transform vrHead;
/// <summary>
/// VrOrigin must be instanciated on Awake(), not in an Update(). It needs the initial localPosition before head tracking is applied to Camera.main
/// </summary>
static VrOrigin()
{
if (vrHead == null)
{
SetVrHead(Camera.main.transform);
}
}
/// <summary> For the most accurate values, this function should be called in Awake() </summary>
/// <param name="HeadNode">ie Camera.main.transform</param>
public static void SetVrHead(Transform HeadNode)
{
vrHead = HeadNode;
startLocalPosition = vrHead.localPosition;
startLocalRotation = vrHead.localRotation;
}
private static void updateOrigin()
{
if (vrHead.parent.hasChanged) // only needs to be updated if the global position has moved. TODO: support grandparent, greatgrandparent, etc being moved
{
vrHead.parent.hasChanged = false;
_position = startLocalPosition + vrHead.parent.position;
_rotation = startLocalRotation * vrHead.parent.rotation; // TODO: work for all rotations, right now only works if the parent has 0 rotation
Debug.Log("rotation updated to " + _rotation.eulerAngles);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment