跳到主要内容

锚点

锚点是在三维空间创建的点,可随底层 AR 系统对现实的理解不断更新,使虚拟物体看起来稳定地固定在用户环境中。

每个锚点包含位置和方向,可以从任意点创建,也可关联命中测试结果以提高可靠性。

使用锚点​

请求会话时传入相应标志:

app.xr.start(camera, pc.XRTYPE_AR, pc.XRSPACE_LOCALFLOOR, {
anchors: true
});

支持​

检查系统是否支持锚点:

if (app.xr.anchors.supported) {
// anchors are supported
}

app.xr.on('start', () => {
if (app.xr.anchors.available) {
// anchors are supported and available
}
});

创建锚点​

可以使用任意位置和旋转创建:

app.xr.anchors.create(position, rotation, (err, anchor) => {
if (!err) {
// new anchor has been created
}
});

更可靠的方法是从命中测试结果创建。

锚点​

锚点的位置和旋转随时可能更新,应用应同步更新关联虚拟对象。

会话期间可动态添加和移除:

app.xr.anchors.on('add', (anchor) => {
const entity = new pc.Entity();

// add a cone for an anchor
entity.addComponent('render', { type: 'cone' });
entity.setLocalScale(0.1, 0.1, 0.1); // 10cm diameter
app.root.addChild(entity);

// transform
entity.setLocalPosition(anchor.getPosition());
entity.setLocalRotation(anchor.getRotation());
entity.translateLocal(0, 0.05, 0); // offset cone

// update cone when anchor changes
anchor.on('change', () => {
entity.setLocalPosition(anchor.getPosition());
entity.setLocalRotation(anchor.getRotation());
entity.translateLocal(0, 0.05, 0); // offset cone
});

// remove cone when anchor is destroyed
anchor.once('destroy', () => {
entity.destroy();
});
});

持久化​

持久化允许跨会话记住锚点,每个来源的数量有限。虚拟物体因此可在不同会话间保持相对现实几何体的位置。

检查是否支持持久化:

if (app.xr.anchors.persistence) {
// application can persist anchors
}

每个锚点可以有 UUID,用于跨会话引用和恢复。

可在会话开始时列出并恢复:

app.xr.on('start', () => {
const uuids = app.xr.anchors.uuids;
for(let i = 0; i < uuids.length; i++) {
app.xr.anchors.restore(uuids[i]);
}
});

单个锚点使用 persist 和 forget 管理:

anchor.persist((err, uuid) => {
if (uuid) {
// anchor has been persisted
}
});
if (anchor.persistent) {
anchor.forget((err) => {
if (!err) {
// anchor is forgotten
}
});
}