跳到主要内容

命中测试

AR/MR 中虚拟与现实可通过多种技术交互。命中测试探测底层 AR 系统估计的现实几何体,选取空间点。

常见用途是将虚拟物体放在现实环境中,使其看起来稳固落地。

可靠性​

底层系统不断理解现实几何体,有的平台使用预先捕获信息,有的通过视觉实时估计,因此可靠性取决于平台。

支持​

检查是否支持:

if (app.xr.hitTest.supported) {
// hit testing is supported
}

命中测试源​

请求开始后获得 HitTestSource,通过事件提供结果,并可管理其生命周期。

最简单方式是沿观察者前向探测:

// start a hit test
app.xr.hitTest.start({
spaceType: pc.XRSPACE_VIEWER, // from a viewer space
callback: (err, hitTestSource) => {
if (err) return;
// subscribe to hit test results
hitTestSource.on('result', (position, rotation) => {
// position and rotation of hit test result
// based on a ray facing forward from the viewer reference space
});
}
});

移除源即可停止:

hitTestSource.remove();

单目触摸屏​

手机等单目设备可根据屏幕触摸开始测试:

app.xr.hitTest.start({
profile: 'generic-touchscreen', // touch screen input sources
callback: (err, hitTestSource) => {
if (err) return;
hitTestSource.on('result', (position, rotation, inputSource) => {
// position and rotation of hit test result
// that will be created from touch on mobile devices
});
}
});

触摸等短暂输入不会立即提供结果,因为源创建是异步操作,结果还取决于底层系统。短暂触摸期间可能没有任何结果。

输入源​

常见方式是从控制器或手的输入射线发起:

inputSource.hitTestStart({
callback: (err, hitTestSource) => {
if (err) return;
hitTestSource.on('result', (position, rotation) => {
// position and rotation of a hit test result
// based on a ray of an input source
});
}
});

任意射线​

也可自定义起点和方向:

const ray = new pc.Ray();

ray.origin.set(0, 1, 0); // start 1 meter above the origin
ray.direction.set(0, -1, 0); // point downwards

app.xr.hitTest.start({
spaceType: pc.XRSPACE_LOCALFLOOR,
offsetRay: ray,
callback: (err, hitTestSource) => {
// hit test source that will sample real world geometry
// from the position where AR session started
}
});

锚点​

底层对平面、网格或点的理解会不断细化,命中几何也随之变化。可根据结果创建锚点,跟随更新,使摆放更稳定可靠:

// subscribe to hit test results
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
// create an anchor using a hit test result
app.xr.anchors.create(hitTestResult, (err, anchor) => {
if (!err) {
// a new anchor has been created
}
});
});