131 lines
3.5 KiB
C#

/*
Copyright © 2016 NaturalPoint Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using UnityEngine;
/// <summary>
/// Implements live tracking of streamed OptiTrack rigid body data onto an object.
/// </summary>
public class OptitrackRigidBody : MonoBehaviour
{
[Tooltip("The ID of the rigid body to track.")]
public int rigidBodyId;
[Tooltip("The name of the prop to track. If set, this will override the rigidBodyId.")]
public string propName;
[Tooltip("Whether to use network compensation for this rigid body.")]
public bool useNetworkCompensation = true;
private OptitrackStreamingClient m_streamingClient;
private bool m_isRigidBodyFound = false;
private int m_resolvedRigidBodyId = -1;
public bool isRigidBodyFound
{
get { return m_isRigidBodyFound; }
}
void Start()
{
m_streamingClient = OptitrackStreamingClient.FindDefaultClient();
if (m_streamingClient == null)
{
Debug.LogError("OptitrackRigidBody: No OptitrackStreamingClient found in scene.", this);
return;
}
// Resolve prop name to ID if provided
if (!string.IsNullOrEmpty(propName))
{
m_resolvedRigidBodyId = m_streamingClient.GetRigidBodyIdByName(propName);
if (m_resolvedRigidBodyId == -1)
{
Debug.LogWarning($"OptitrackRigidBody: Could not find rigid body with name '{propName}'", this);
return;
}
}
else
{
m_resolvedRigidBodyId = rigidBodyId;
}
m_streamingClient.RegisterRigidBody(this, m_resolvedRigidBodyId);
}
#if UNITY_2017_1_OR_NEWER
void OnEnable()
{
Application.onBeforeRender += OnBeforeRender;
}
void OnDisable()
{
Application.onBeforeRender -= OnBeforeRender;
}
void OnBeforeRender()
{
UpdatePose();
}
#endif
void Update()
{
if (m_streamingClient == null || m_resolvedRigidBodyId == -1)
return;
OptitrackRigidBodyState rbState = m_streamingClient.GetLatestRigidBodyState(m_resolvedRigidBodyId, useNetworkCompensation);
if (rbState != null)
{
m_isRigidBodyFound = rbState.IsTracked;
if (m_isRigidBodyFound)
{
transform.position = rbState.Pose.Position;
transform.rotation = rbState.Pose.Orientation;
}
}
else
{
m_isRigidBodyFound = false;
}
}
void UpdatePose()
{
if (m_streamingClient == null || m_resolvedRigidBodyId == -1)
return;
OptitrackRigidBodyState rbState = m_streamingClient.GetLatestRigidBodyState(m_resolvedRigidBodyId, useNetworkCompensation);
if (rbState != null)
{
m_isRigidBodyFound = rbState.IsTracked;
if (m_isRigidBodyFound)
{
transform.position = rbState.Pose.Position;
transform.rotation = rbState.Pose.Orientation;
}
}
}
}