/**************************************************************************** * Copyright 2019 Nreal Techonology Limited. All rights reserved. * * This file is part of NRSDK. * * https://www.nreal.ai/ * *****************************************************************************/ namespace NRKernal { using System; using System.Collections.Generic; using UnityEngine; /// Update the transform of a trackable. public partial class NRAnchor : MonoBehaviour { /// Dictionary of anchors. private static Dictionary m_AnchorDict = new Dictionary(); /// The trackable. public NRTrackable Trackable; /// True if is session destroyed, false if not. private bool m_IsSessionDestroyed; /// Create a anchor for the trackable object. /// Instantiate a NRAnchor object which Update trackable pose every frame. /// NRAnchor. public static NRAnchor Factory(NRTrackable trackable) { if (trackable == null) { return null; } NRAnchor result; if (m_AnchorDict.TryGetValue(trackable.GetDataBaseIndex(), out result)) { return result; } NRAnchor anchor = (new GameObject()).AddComponent(); anchor.gameObject.name = "Anchor"; anchor.Trackable = trackable; m_AnchorDict.Add(trackable.GetDataBaseIndex(), anchor); return anchor; } /// Updates this object. private void Update() { if (Trackable == null) { NRDebugger.Error("NRAnchor components instantiated outside of NRInternel are not supported. " + "Please use a 'Create' method within NRInternel to instantiate anchors."); return; } if (IsSessionDestroyed()) { return; } var pose = Trackable.GetCenterPose(); transform.position = pose.position; transform.rotation = pose.rotation; } /// Executes the 'destroy' action. private void OnDestroy() { if (Trackable == null) { return; } m_AnchorDict.Remove(Trackable.GetDataBaseIndex()); } /// Check whether the session is already destroyed. /// True if session destroyed, false if not. private bool IsSessionDestroyed() { if (!m_IsSessionDestroyed) { var subsystem = NRSessionManager.Instance.TrackableFactory.TrackableSubsystem; if (subsystem != Trackable.TrackableSubsystem) { Debug.LogErrorFormat("The session which created this anchor has been destroyed. " + "The anchor on GameObject {0} can no longer update.", this.gameObject != null ? this.gameObject.name : "Unknown"); m_IsSessionDestroyed = true; } } return m_IsSessionDestroyed; } } }