使用 Jetpack XR 的 ARCore 追蹤裝置姿勢

適用 XR 裝置
這份指南可協助您為這類 XR 裝置打造體驗。
XR 頭戴式裝置
有線 XR 眼鏡
AI 眼鏡

透過 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 代表裝置相對於追蹤原點的位置 (平移) 和方向 (旋轉)。在應用程式中使用這項資訊,提升應用程式體驗:

  1. 提供精確的位置導覽指示:位置資料可協助使用者辨別方向,並透過疊加的數位內容導覽周遭環境。

  2. 中繼世界對齊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 說明文件,瞭解如何將裝置姿勢轉換為地理空間姿勢