借助 ARCore for Jetpack XR,您的应用可以检索设备的姿态:即设备相对于世界原点的方向(俯仰角、偏航角、滚转角)和位置 (X, Y, Z)。
您可以使用此信息在现实世界中渲染数字内容,或将设备姿态转换为地理空间姿态,从而生成具备位置感知的数据。
访问会话
通过 Jetpack XR 运行时 Session 访问设备姿态信息,该会话必须由您的应用创建。
配置会话
默认情况下,XR 会话中未启用设备姿态信息。如需让应用能够检索设备姿态信息,请配置会话并设置 DeviceTrackingMode.LAST_KNOWN 模式:
// Define the configuration object to enable tracking device pose. val newConfig = session.config.copy( deviceTracking = DeviceTrackingMode.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 设备都支持 DeviceTrackingMode.LAST_KNOWN 模式。如果 Session.configure() 成功,则设备支持此模式。
获取设备姿态
会话配置完成后,您可以使用 ArDevice 对象获取设备在 AR 坐标系中的姿态:
// Get the ArDevice instance val arDevice = ArDevice.getInstance(session) // There are two ways to get the device pose. // 1. Get the current device pose once. // This is the device's position and orientation relative to the tracking origin. val devicePose = arDevice.state.value.devicePose processDevicePose(devicePose) // 2. Continuously receive updates for the device pose. // `collect` is a suspending function that will run indefinitely and process new poses. arDevice.state.collect { state -> processDevicePose(state.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 内容将从临时、孤立的体验转变为现实世界中永久存在、可广泛共享且具有情境感知能力的功能。
如需了解如何将设备姿态转换为地理空间姿态,请参阅 Geospatial API 文档。