透過 Jetpack XR 適用的 ARCore,應用程式可以擷取裝置的姿勢:裝置相對於世界原點的方向 (俯仰、偏航、滾動) 和位置 (X、Y、Z)。
您可以使用這項資訊在真實世界中算繪數位內容,或將裝置姿勢轉換為地理空間姿勢,產生位置感知資料。
存取工作階段
透過 Jetpack XR 執行階段 Session 存取裝置姿勢資訊,應用程式必須建立該執行階段。
設定工作階段
XR 工作階段預設不會啟用裝置姿勢資訊。如要讓應用程式擷取裝置姿勢資訊,請設定工作階段並設定 DeviceTrackingMode.SPATIAL 模式:
// Define the configuration object to enable tracking device pose. val newConfig = Config.Builder(session.config) .setDeviceTracking(DeviceTrackingMode.SPATIAL) .build() // 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.SPATIAL 模式。如果 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 代表裝置相對於追蹤原點的位置 (平移) 和方向 (旋轉)。在應用程式中使用這項資訊,提升應用程式體驗:
- 提供位置精確的導航指示:使用位置資料,協助使用者辨別方向,並透過疊加的數位內容,引導他們在周遭環境中移動。
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. */) }