You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Unity中对齐MRTK Playspace与Hololens 2追踪的二维码

问题

在Unity 2021 LTS中使用MRTK 2开发Hololens 2应用时,需将3D物体相对于追踪到的二维码显示:扫描桌面平放的二维码后,让物体在其后方数厘米处并匹配其旋转。由于物体带有物理关节,无法直接移动物体匹配二维码位姿,只能移动作为相机父物体的MRTK Playspace。

尝试了以下代码(anchor是带位置偏移的二维码子Transform):

MixedRealityPlayspace.Position -= anchor.position;
MixedRealityPlayspace.RotateAround(Vector3.zero, Vector3.up, anchor.rotation.eulerAngles.y);

此方案位置正确,但旋转始终存在偏差(有时细微,有时达约30度)。代码在二维码检测1秒后执行一次,偏差过大非单次追踪误差所致,且不知如何持续应用变换。

二维码追踪基于微软的MRTK QR Code sample for Unity,已在SpatialGraphNodeTracker.cs中修改,将检测到的二维码旋转乘以Quaternion.Euler(90, 90, 90)以获取Y轴朝上的姿态,二维码的位姿是准确的。曾尝试World Locking Tools,但未找到适配场景的信息。

请问如何重新定位Playspace,使3D物体与追踪二维码实现精准对齐?

解决方案

1. 修正旋转计算逻辑

单独提取Y轴欧拉角会丢失二维码的X/Z轴姿态信息(即使平放,追踪位姿也可能存在微小倾斜),导致旋转偏差。改用四元数逆变换计算Playspace的目标旋转:

// 通过逆旋转抵消二维码的姿态,让物体对齐二维码
Quaternion targetPlayspaceRotation = Quaternion.Inverse(anchor.rotation) * MixedRealityPlayspace.Rotation;
MixedRealityPlayspace.Rotation = targetPlayspaceRotation;

2. 统一坐标系下的位置调整

直接使用世界空间偏移可能因坐标系差异出现误差,建议先转换到Playspace本地空间再计算偏移:

// 将anchor的世界位置转换为Playspace本地位置,再反向偏移
Vector3 localAnchorPos = MixedRealityPlayspace.Transform.InverseTransformPoint(anchor.position);
MixedRealityPlayspace.Position -= MixedRealityPlayspace.Transform.TransformVector(localAnchorPos);

3. 持续平滑校准

单次执行易受瞬时追踪误差影响,建议在二维码稳定追踪时,每帧平滑更新Playspace位姿:

public float smoothSpeed = 0.1f;
private bool isTrackingQRCode = false; // 需根据二维码检测逻辑设置此状态

void Update()
{
    if (isTrackingQRCode && anchor != null)
    {
        // 平滑调整位置
        Vector3 targetPosition = MixedRealityPlayspace.Position - anchor.position;
        MixedRealityPlayspace.Position = Vector3.Lerp(MixedRealityPlayspace.Position, targetPosition, smoothSpeed);
        
        // 平滑调整旋转
        Quaternion targetRotation = Quaternion.Inverse(anchor.rotation) * MixedRealityPlayspace.Rotation;
        MixedRealityPlayspace.Rotation = Quaternion.Lerp(MixedRealityPlayspace.Rotation, targetRotation, smoothSpeed);
    }
}

4. 验证二维码位姿准确性

在场景中添加Gizmo实时可视化anchor的位姿,确认其旋转是否完全符合Y轴朝上的预期。若anchor旋转本身存在偏差,需调整SpatialGraphNodeTracker.cs中的旋转修正代码:

Quaternion qrRotation = spatialGraphNode.GetRotation(FrameTime.OnUpdate);
// 根据实际扫码姿态调整欧拉角,原90,90,90可能过度旋转
qrRotation *= Quaternion.Euler(90, 0, 0); 
transform.rotation = qrRotation;

内容的提问来源于stack exchange,提问作者itkdk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:03:14