//========================================================== // // Copyright (c) Guangzhou Shixiang Technology Co.,Ltd. // All rights reserved. // //========================================================== using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using GxrSdk; using TMPro; using UnityEngine; public class ObjectTrackingResultInfo : MonoBehaviour, IGxrObjectTrackingHandler { [SerializeField] private TextMeshPro textTotal; [SerializeField] private TextMeshPro textCount; [SerializeField] private TextMeshPro textResult; private readonly StringBuilder _stringBuilder = new StringBuilder(); // 当前帧中跟踪到的id private readonly List _currentTrackedIds = new List(); // 保存上一帧中跟踪到的id private readonly List _lastTrackedIds = new List(); // 识别到的总次数 // 当前帧中跟踪到的id,如果在上一帧中没有,则总次数加一 private int _totalNum = 0; void OnEnable() { GxrSystemAccessor.TrackingSystem?.RegisterHandler(this); } void OnDisable() { GxrSystemAccessor.TrackingSystem?.UnregisterHandler(this); } public void OnObjectTrackingUpdated(GxrObjectTrackingEventData eventData) { var trackingResults = eventData.TrackingResults; UpdateCountText(trackingResults.Count); _stringBuilder.Clear(); for (int i = 0; i < trackingResults.Count; ++i) { var trackingResult = trackingResults[i]; uint id = trackingResult.TrackerId; var position = trackingResult.Pose.position; var rotation = trackingResult.Pose.rotation; var localPosition = trackingResult.LocalPose.position; var localRotation = trackingResult.LocalPose.rotation; _stringBuilder.Append($"Id:{id},Position:{position:F3},Rotation:{rotation.eulerAngles:F3}\n" + $"LocalPosition:{localPosition:F3},LocalRotation:{localRotation.eulerAngles:F3}\n"); } UpdateResultText(_stringBuilder.ToString()); UpdateTotalNum(trackingResults); } private void UpdateCountText(int count) { if (textCount != null) { textCount.text = $"Count: {count}"; } } private void UpdateResultText(string result) { if (textResult != null) { textResult.text = result; } } /// /// 更新识别到的总次数 /// 当前帧中跟踪到的id,如果在上一帧中没有,则总次数加一 /// /// private void UpdateTotalNum(ReadOnlyCollection trackingResults) { _currentTrackedIds.Clear(); for (var i = 0; i < trackingResults.Count; ++i) { var trackedId = trackingResults[i].TrackerId; _currentTrackedIds.Add(trackedId); if (!_lastTrackedIds.Exists(id => id == trackedId)) { ++_totalNum; if (textTotal != null) { textTotal.text = $"Total: {_totalNum}"; } } } _lastTrackedIds.Clear(); _currentTrackedIds.ForEach(i => _lastTrackedIds.Add(i)); } public void OnTargetFound() { Debug.Log($"[ObjectTrackingResultInfo][OnTargetFound] "); } public void OnTargetLost() { Debug.Log($"[ObjectTrackingResultInfo][OnTargetLost] "); } public void OnTargetUpdated(Pose worldPose) { Debug.Log($"[ObjectTrackingResultInfo][OnTargetUpdated] {worldPose.position:F3},{worldPose.rotation:F3}"); } }