借助适用于 Jetpack XR 的 ARCore,您的应用可以检索设备的姿态:设备相对于世界原点的方向(俯仰角、偏航角、滚转角)和位置 (X, Y, Z)。
使用此信息在现实世界中呈现数字内容,或将设备姿态转换为地理空间姿态,以生成位置感知数据。
访问会话
通过 Jetpack XR Runtime Session 访问设备姿态信息,应用必须创建该对象。
配置会话
在 XR 会话中,设备姿态信息默认处于未启用状态。如需让应用能够检索设备姿态信息,请配置会话并设置 HeadTrackingMode.LAST_KNOWN 模式:
// Define the configuration object to enable tracking device pose.
val newConfig = session.config.copy(
headTrackingMode = Config.HeadTrackingMode.LAST_KNOWN
)
// Apply the configuration to the session.
try {
when (val configResult = session.configure(newConfig)) {
is SessionConfigureSuccess -> {
// The session is now configured to track the device's pose.
}
else -> {
// Catch-all for other configuration errors returned using the result class.
}
}
} catch (e: UnsupportedOperationException) {
// Handle configuration failure. For example, if the specific mode is not supported on the current device or API version.
}
并非所有 XR 设备都支持 HeadTrackingMode.LAST_KNOWN 模式。如果 Session.configure() 成功,则设备支持此模式。
获取设备姿势
会话配置完成后,您可以使用 ArDevice 对象获取设备在 AR 坐标系中的姿势:
// Get the ArDevice instance
val arDevice = ArDevice.getInstance(session)
// Collect the state to process the device pose
arDevice.state.collect { state ->
// processDevicePose gets called automatically when a new pose is available.
processDevicePose(state.devicePose)
}
// Or, get the current device Pose from the AR Device's state.
// This is the device's position and orientation relative to the tracking origin.
val devicePose = ArDevice.getInstance(session).state.value.devicePose
获取设备姿势的平移和旋转
设备 Pose 表示设备相对于跟踪原点的位置(平移)和方向(旋转)。在应用中使用这些信息来提升应用体验:
提供位置精确的导航说明:位置数据可用于帮助用户确定自己的方位,并在叠加的数字内容的帮助下浏览周围环境。
中间世界对齐:此姿势由 Geospatial API 使用,用于计算真实世界位置。
fun processDevicePose(pose: Pose) {
// Extract Translation and Rotation
val translation = pose.translation // Vector3(x, y, z)
val rotation = pose.rotation // Quaternion (x, y, z, w)
TODO(/* Use the translation and rotation in your app. */)
}
将设备姿势转换为地理空间姿势
获得设备姿态后,您可以从中获取地理空间姿态。 转换为地理空间姿势后,您的 AR 内容将从临时、孤立的体验转变为现实世界中永久、普遍共享且具有情境感知功能的特性。
如需了解如何将设备姿势转换为地理空间姿势,请参阅我们的地理空间 API 文档。