using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class HumanBodyTracker : MonoBehaviour
{
[SerializeField]
[Tooltip("The Skeleton prefab to be controlled.")]
GameObject m_SkeletonPrefab;
[SerializeField]
[Tooltip("The ARHumanBodyManager which will produce body tracking events.")]
ARHumanBodyManager m_HumanBodyManager;
///
/// Get/Set the ARHumanBodyManager.
///
public ARHumanBodyManager humanBodyManager
{
get { return m_HumanBodyManager; }
set { m_HumanBodyManager = value; }
}
///
/// Get/Set the skeleton prefab.
///
public GameObject skeletonPrefab
{
get { return m_SkeletonPrefab; }
set { m_SkeletonPrefab = value; }
}
Dictionary m_SkeletonTracker = new Dictionary();
void OnEnable()
{
Debug.Assert(m_HumanBodyManager != null, "Human body manager is required.");
m_HumanBodyManager.humanBodiesChanged += OnHumanBodiesChanged;
}
void OnDisable()
{
if (m_HumanBodyManager != null)
m_HumanBodyManager.humanBodiesChanged -= OnHumanBodiesChanged;
}
void OnHumanBodiesChanged(ARHumanBodiesChangedEventArgs eventArgs)
{
BoneController boneController;
foreach (var humanBody in eventArgs.added)
{
if (!m_SkeletonTracker.TryGetValue(humanBody.trackableId, out boneController))
{
Debug.Log($"Adding a new skeleton [{humanBody.trackableId}].");
var newSkeletonGO = Instantiate(m_SkeletonPrefab, humanBody.transform);
boneController = newSkeletonGO.GetComponent();
m_SkeletonTracker.Add(humanBody.trackableId, boneController);
}
boneController.InitializeSkeletonJoints();
boneController.ApplyBodyPose(humanBody);
}
foreach (var humanBody in eventArgs.updated)
{
if (m_SkeletonTracker.TryGetValue(humanBody.trackableId, out boneController))
{
boneController.ApplyBodyPose(humanBody);
}
}
foreach (var humanBody in eventArgs.removed)
{
Debug.Log($"Removing a skeleton [{humanBody.trackableId}].");
if (m_SkeletonTracker.TryGetValue(humanBody.trackableId, out boneController))
{
Destroy(boneController.gameObject);
m_SkeletonTracker.Remove(humanBody.trackableId);
}
}
}
}