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

Spark AR:如何实现物体锚定图像追踪器后固定在屏幕显示?

在Spark AR中实现图像追踪器定位后物体固定显示的方案

直接将物体锚定到图像追踪器会导致追踪器不可见时物体同步隐藏,因为追踪器的可见性会直接关联其子物体的显示状态。要实现「以追踪器为初始定位参考,之后固定物体位置」的需求,需要通过脚本记录追踪器可见时的物体空间位置,后续将物体脱离追踪器的依赖,固定在相机空间中。

步骤1:基础场景设置

  • 添加图像追踪器,上传目标图像后,在Inspector面板中关闭追踪器的可视化(取消勾选Visualization选项),避免追踪器本身显示在画面中。
  • 创建需要显示的目标物体,先暂时将其作为图像追踪器的子物体,调整好相对位置(比如放在追踪器的正上方、前方等),位置调好后将物体移到场景根节点或相机节点下,解除与追踪器的父子关联。

步骤2:编写核心脚本(JavaScript)

通过监听图像追踪器的可见状态,记录物体的世界空间位置,之后每帧将物体固定在该位置上:

const Scene = require('Scene');
const Diagnostics = require('Diagnostics');

// 获取场景中的图像追踪器和目标物体
const imageTracker = Scene.root.find('imageTracker0');
const targetObject = Scene.root.find('targetObject');

// 存储固定位置与旋转的变量
let fixedWorldPos = null;
let fixedWorldRot = null;

// 监听追踪器的可见状态
imageTracker.trackedImage.exists.monitor().subscribe((event) => {
  if (event.newValue) {
    // 追踪器首次可见时,记录物体当前的世界空间位置和旋转
    fixedWorldPos = targetObject.worldTransform.position.clone();
    fixedWorldRot = targetObject.worldTransform.rotation.clone();
    Diagnostics.log('已锁定物体位置');
  }
});

// 每帧更新物体状态
Scene.onUpdate(() => {
  if (fixedWorldPos && fixedWorldRot) {
    // 物体固定在记录的位置与旋转角度
    targetObject.worldTransform.position = fixedWorldPos;
    targetObject.worldTransform.rotation = fixedWorldRot;
  } else {
    // 未锁定位置前,物体跟随追踪器移动(可选,也可设置物体隐藏)
    targetObject.worldTransform.position = imageTracker.worldTransform.position;
    targetObject.worldTransform.rotation = imageTracker.worldTransform.rotation;
  }
});

步骤3:优化体验(可选)

如果需要避免误触发(比如追踪器短暂识别就固定位置),可以添加延迟锁定逻辑:

const Scene = require('Scene');
const Diagnostics = require('Diagnostics');

const imageTracker = Scene.root.find('imageTracker0');
const targetObject = Scene.root.find('targetObject');

let fixedWorldPos = null;
let fixedWorldRot = null;
let trackStartTime = null;
const lockDelay = 1500; // 1.5秒后锁定位置

imageTracker.trackedImage.exists.monitor().subscribe((event) => {
  if (event.newValue) {
    trackStartTime = Date.now();
  } else {
    trackStartTime = null;
  }
});

Scene.onUpdate(() => {
  // 满足延迟条件且未锁定位置时,记录坐标
  if (trackStartTime && Date.now() - trackStartTime >= lockDelay && !fixedWorldPos) {
    fixedWorldPos = targetObject.worldTransform.position.clone();
    fixedWorldRot = targetObject.worldTransform.rotation.clone();
    Diagnostics.log('延迟锁定完成');
  }

  if (fixedWorldPos && fixedWorldRot) {
    targetObject.worldTransform.position = fixedWorldPos;
    targetObject.worldTransform.rotation = fixedWorldRot;
  } else {
    targetObject.worldTransform.position = imageTracker.worldTransform.position;
    targetObject.worldTransform.rotation = imageTracker.worldTransform.rotation;
  }
});

注意事项

  • 确保脚本已添加到项目中,且在Spark AR Studio中正确关联了追踪器和物体的名称。
  • 测试时建议在实际设备上验证,预览窗口的图像追踪效果可能与设备存在差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:06