如何在 Unity 中使用 Azure Spatial Anchors 建立和尋找錨點

Azure Spatial Anchors 可讓您在不同裝置之間共用世界錨點。 它支持數個不同的開發環境。 在本文中,我們將探討如何使用 Unity 中的 Azure Spatial Anchors SDK 來:

  • 正確設定和管理 Azure Spatial Anchors 會話。
  • 在本機錨點上建立和設定屬性。
  • 將它們上傳至雲端。
  • 找出並刪除雲端空間錨點。

必要條件

若要完成本指南,請確定您:

Cross Platform

初始化會話

SDK 的主要進入點是代表您工作階段的類別。 您通常會在類別中宣告一個字段,以管理您的檢視和原生AR會話。

深入瞭解 CloudSpatialAnchorSession 類別。

    CloudSpatialAnchorSession cloudSession;
    // In your view handler
    this.cloudSession = new CloudSpatialAnchorSession();

設定驗證

若要存取服務,您必須提供帳戶密鑰、存取令牌或 Microsoft Entra 驗證令牌。 您也可以在 [驗證概念] 頁面中深入瞭解這一點。

帳戶金鑰

帳戶金鑰是一種認證,可讓您的應用程式向 Azure Spatial Anchors 服務進行驗證。 帳戶金鑰的用途是協助您快速開始使用。 特別是在應用程式與 Azure Spatial Anchors 整合的開發階段。 因此,您可以在開發期間將其內嵌在用戶端應用程式中,以使用帳戶密鑰。 在開發之後進行時,強烈建議您移至生產層級、存取令牌支援或 Microsoft Entra 使用者驗證的驗證機制。 若要取得用於開發的帳戶密鑰,請流覽您的 Azure Spatial Anchors 帳戶,並流覽至 [金鑰] 索引卷標。

深入瞭解 SessionConfiguration 類別。

    this.cloudSession.Configuration.AccountKey = @"MyAccountKey";

存取權杖

存取令牌是使用 Azure Spatial Anchors 進行驗證的更健全方法。 特別是當您準備應用程式以進行生產環境部署時。 此方法的摘要是設定用戶端應用程式可以安全地進行驗證的後端服務。 您的後端服務介面在運行時間與 AAD,以及 Azure Spatial Anchors Secure Token Service 來要求存取令牌。 此令牌接著會傳遞至用戶端應用程式,並在 SDK 中用來向 Azure Spatial Anchors 進行驗證。

    this.cloudSession.Configuration.AccessToken = @"MyAccessToken";

如果未設定存取令牌,您必須處理 TokenRequired 事件,或在委派通訊協議上實 tokenRequired 作 方法。

您可以在事件自變數上設定 屬性,以同步處理事件。

深入瞭解 TokenRequiredDelegate 委派。

    this.cloudSession.TokenRequired += (object sender, TokenRequiredEventArgs args) =>
    {
        args.AccessToken = @"MyAccessToken";
    };

如果您需要在處理程式中執行異步工作,您可以藉由要求 deferral 對象,然後完成令牌來延遲設定令牌,如下列範例所示。

    this.cloudSession.TokenRequired += async (object sender, TokenRequiredEventArgs args) =>
    {
        var deferral = args.GetDeferral();
        string myToken = await MyGetTokenAsync();
        if (myToken != null) args.AccessToken = myToken;
        deferral.Complete();
    };

Microsoft Entra 驗證

Azure Spatial Anchors 也允許應用程式向使用者 Microsoft Entra ID (Active Directory) 令牌進行驗證。 例如,您可以使用 Microsoft Entra 令牌與 Azure Spatial Anchors 整合。 如果 Enterprise 在 Microsoft Entra ID 中維護使用者,您可以在 Azure Spatial Anchors SDK 中提供使用者 Microsoft Entra 令牌。 這麼做可讓您直接向屬於相同 Microsoft Entra 租使用者一部分的帳戶驗證 Azure Spatial Anchors 服務。

    this.cloudSession.Configuration.AuthenticationToken = @"MyAuthenticationToken";

如同存取令牌,如果未設定 Microsoft Entra 令牌,您必須處理 TokenRequired 事件,或在委派通訊協定上實作 tokenRequired 方法。

您可以在事件自變數上設定 屬性,以同步處理事件。

    this.cloudSession.TokenRequired += (object sender, TokenRequiredEventArgs args) =>
    {
        args.AuthenticationToken = @"MyAuthenticationToken";
    };

如果您需要在處理程式中執行異步工作,您可以藉由要求 deferral 對象,然後完成令牌來延遲設定令牌,如下列範例所示。

    this.cloudSession.TokenRequired += async (object sender, TokenRequiredEventArgs args) =>
    {
        var deferral = args.GetDeferral();
        string myToken = await MyGetTokenAsync();
        if (myToken != null) args.AuthenticationToken = myToken;
        deferral.Complete();
    };

設定會話

Start() 用 以讓您的工作階段處理環境數據。

若要處理會話所引發的事件,請附加事件處理程式。

深入瞭解 Start 方法。

#if UNITY_ANDROID || UNITY_IOS
    this.cloudSession.Session = aRSession.subsystem.nativePtr.GetPlatformPointer();
#elif UNITY_WSA || WINDOWS_UWP
    // No need to set a native session pointer for HoloLens.
#else
    throw new NotSupportedException("The platform is not supported.");
#endif

    this.cloudSession.Start();

提供會話的畫面格

空間錨點會話的運作方式是對應用戶周圍的空間。 這樣做有助於判斷錨點所在的位置。 行動平臺 (iOS 和 Android) 需要原生呼叫相機摘要,才能從您平臺的 AR 連結庫取得畫面。 相反地,HoloLens 會持續掃描環境,因此不需要像行動平臺上這樣的特定呼叫。

深入瞭解 ProcessFrame 方法。

#if UNITY_ANDROID || UNITY_IOS
    XRCameraFrame xRCameraFrame;
    if (aRCameraManager.subsystem.TryGetLatestFrame(cameraParams, out xRCameraFrame))
    {
        long latestFrameTimeStamp = xRCameraFrame.timestampNs;

        bool newFrameToProcess = latestFrameTimeStamp > lastFrameProcessedTimeStamp;

        if (newFrameToProcess)
        {
            session.ProcessFrame(xRCameraFrame.nativePtr.GetPlatformPointer());
            lastFrameProcessedTimeStamp = latestFrameTimeStamp;
        }
    }
#endif

提供意見反應給使用者

您可以撰寫程式代碼來處理工作階段更新的事件。 每次會話改善您對周圍環境的理解時,就會引發此事件。 這樣做可讓您:

  • 使用 類別 UserFeedback ,在裝置移動時向使用者提供意見反應,而會話會更新其環境瞭解。 若要這樣做:
  • 判斷哪些時間點有足夠的追蹤空間數據來建立空間錨點。 您可以使用 或 RecommendedForCreateProgress來判斷這一ReadyForCreateProgress點。 一旦 ReadyForCreateProgress 超過 1,我們有足夠的數據可儲存雲端空間錨點,不過我們建議您等 RecommendedForCreateProgress 到 1 以上才能這麼做。

深入瞭解 SessionUpdatedDelegate 委派。

    this.cloudSession.SessionUpdated += (object sender, SessionUpdatedEventArgs args) =>
    {
        var status = args.Status;
        if (status.UserFeedback == SessionUserFeedback.None) return;
        this.feedback = $"Feedback: {Enum.GetName(typeof(SessionUserFeedback), status.UserFeedback)} -" +
            $" Recommend Create={status.RecommendedForCreateProgress: 0.#%}";
    };

建立雲端空間錨點

若要建立雲端空間錨點,請先在平臺的AR系統中建立錨點,然後建立雲端對應專案。 您可以使用 CreateAnchorAsync() 方法。

深入瞭解 CloudSpatialAnchor 類別。

    // Create a local anchor, perhaps by hit-testing and spawning an object within the scene
    Vector3 hitPosition = new Vector3();
#if UNITY_ANDROID || UNITY_IOS
    Vector2 screenCenter = new Vector2(0.5f, 0.5f);
    List<ARRaycastHit> aRRaycastHits = new List<ARRaycastHit>();
    if(arRaycastManager.Raycast(screenCenter, aRRaycastHits) && aRRaycastHits.Count > 0)
    {
        ARRaycastHit hit = aRRaycastHits[0];
        hitPosition = hit.pose.position;
    }
#elif WINDOWS_UWP || UNITY_WSA
    RaycastHit hit;
    if (this.TryGazeHitTest(out hit))
    {
        hitPosition = hit.point;
    }
#endif

    Quaternion rotation = Quaternion.AngleAxis(0, Vector3.up);
    this.localAnchor = GameObject.Instantiate(/* some prefab */, hitPosition, rotation);
    this.localAnchor.AddComponent<CloudNativeAnchor>();

    // If the user is placing some application content in their environment,
    // you might show content at this anchor for a while, then save when
    // the user confirms placement.
    CloudNativeAnchor cloudNativeAnchor = this.localAnchor.GetComponent<CloudNativeAnchor>();
    if (cloudNativeAnchor.CloudAnchor == null) { await cloudNativeAnchor.NativeToCloud(); }  
    CloudSpatialAnchor cloudAnchor = cloudNativeAnchor.CloudAnchor;
    await this.cloudSession.CreateAnchorAsync(cloudAnchor);
    this.feedback = $"Created a cloud anchor with ID={cloudAnchor.Identifier}");

如先前所述,您必須先擷取足夠的環境數據,才能嘗試建立新的雲端空間錨點。 這表示 ReadyForCreateProgress 必須高於 1,不過我們建議您等到 RecommendedForCreateProgress 1 以上才能這麼做。

深入瞭解 GetSessionStatusAsync 方法。

    SessionStatus value = await this.cloudSession.GetSessionStatusAsync();
    if (value.RecommendedForCreateProgress < 1.0f) return;
    // Issue the creation request ...

設定屬性

當您儲存雲端空間錨點時,您可以選擇新增一些屬性。 如同要儲存的物件類型,或基本屬性,例如是否應該啟用互動。 這樣做在探索時很有用:您可以立即為用戶轉譯物件,例如具有空白內容的圖片框。 然後,背景中的不同下載會取得其他狀態詳細數據,例如要顯示在框架中的圖片。

深入瞭解 AppProperties 屬性。

    CloudSpatialAnchor cloudAnchor = new CloudSpatialAnchor() { LocalAnchor = localAnchor };
    cloudAnchor.AppProperties[@"model-type"] = @"frame";
    cloudAnchor.AppProperties[@"label"] = @"my latest picture";
    await this.cloudSession.CreateAnchorAsync(cloudAnchor);

更新屬性

若要更新錨點上的屬性,您可以使用 UpdateAnchorProperties() 方法。 如果兩個或多個裝置同時嘗試更新相同錨點的屬性,我們會使用開放式並行存取模型。 這表示第一次寫入將會獲勝。 所有其他寫入都會收到「並行」錯誤:需要重新整理屬性,然後再試一次。

深入瞭解 UpdateAnchorPropertiesAsync 方法。

    CloudSpatialAnchor anchor = /* locate your anchor */;
    anchor.AppProperties[@"last-user-access"] = @"just now";
    await this.cloudSession.UpdateAnchorPropertiesAsync(anchor);

在服務上建立錨點之後,您無法更新錨點的位置 - 您必須建立新的錨點,並刪除舊的錨點以追蹤新位置。

如果您不需要找到錨點來更新其屬性,您可以使用 GetAnchorPropertiesAsync() 方法,這個方法會 CloudSpatialAnchor 傳回具有屬性的物件。

深入瞭解 GetAnchorPropertiesAsync 方法。

    var anchor = await cloudSession.GetAnchorPropertiesAsync(@"anchorId");
    if (anchor != null)
    {
        anchor.AppProperties[@"last-user-access"] = @"just now";
        await this.cloudSession.UpdateAnchorPropertiesAsync(anchor);
    }

設定到期日

您也可以將錨點設定為在未來的指定日期自動到期。 當錨點到期時,它將不再找到或更新。 只有在建立錨點時,才能設定到期日,再將它儲存至雲端。 之後無法更新到期日。 如果在建立錨點期間未設定到期,錨點只會在手動刪除時到期。

深入瞭解 Expiration 屬性。

    cloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7);

找出雲端空間錨點

能夠找出先前儲存的雲端空間錨點,是使用 Azure Spatial Anchors 的主要原因之一。 為此,我們使用「監看員」。 您一次只能使用一個監看員;不支援多個監看員。 監看員可以找到雲端空間錨點,有數種不同的方式(也稱為 錨點尋找策略)。 您可以一次在監看員上使用一個策略。

注意

每次找到錨點時,Azure Spatial Anchors 都會嘗試使用收集的環境數據來增強錨點上的視覺資訊。 如果您在尋找錨點時遇到問題,建立錨點可能會很有用,然後從不同的角度和光源條件找出它數次。

如果您要依標識碼尋找雲端空間錨點,您可以將雲端空間錨點標識符儲存在應用程式的後端服務中,並讓所有可正確向它驗證的裝置存取。 如需此範例,請參閱 教學課程:跨裝置共享空間錨點。

具現化AnchorLocateCriteria對象、設定您要尋找的標識碼,並提供 您的 AnchorLocateCriteria,並在會話上叫CreateWatcher用 方法。

深入瞭解 CreateWatcher 方法。

    AnchorLocateCriteria criteria = new AnchorLocateCriteria();
    criteria.Identifiers = new string[] { @"id1", @"id2", @"id3" };
    this.cloudSession.CreateWatcher(criteria);

建立監看員之後, AnchorLocated 每個要求的錨點都會引發事件。 當錨點位於或錨點找不到時,就會引發此事件。 如果發生這種情況,則會在狀態中說明原因。 處理監看員的所有錨點、找到或找不到之後,事件 LocateAnchorsCompleted 就會引發。 每個監看員的限制為35個標識碼。

深入瞭解 AnchorLocatedDelegate 委派。

    this.cloudSession.AnchorLocated += (object sender, AnchorLocatedEventArgs args) =>
    {
        switch (args.Status)
        {
            case LocateAnchorStatus.Located:
                CloudSpatialAnchor foundAnchor = args.Anchor;
                // Go add your anchor to the scene...
                break;
            case LocateAnchorStatus.AlreadyTracked:
                // This anchor has already been reported and is being tracked
                break;
            case LocateAnchorStatus.NotLocatedAnchorDoesNotExist:
                // The anchor was deleted or never existed in the first place
                // Drop it, or show UI to ask user to anchor the content anew
                break;
            case LocateAnchorStatus.NotLocated:
                // The anchor hasn't been found given the location data
                // The user might in the wrong location, or maybe more data will help
                // Show UI to tell user to keep looking around
                break;
        }
    }

刪除錨點

當不再使用 時刪除錨點是早期納入開發流程和做法的好作法,以讓您的 Azure 資源保持清除狀態。

深入瞭解 DeleteAnchorAsync 方法。

    await this.cloudSession.DeleteAnchorAsync(cloudAnchor);
    // Perform any processing you may want when delete finishes

刪除錨點而不尋找

如果您找不到錨點,但仍想要刪除它,您可以使用 GetAnchorPropertiesAsync 採用 anchorId 做為輸入的 API 來取得 CloudSpatialAnchor 物件。 然後,您可以將這個對象傳遞至 DeleteAnchorAsync 以刪除它。

var anchor = await cloudSession.GetAnchorPropertiesAsync(@"anchorId");
await this.cloudSession.DeleteAnchorAsync(anchor);

暫停、重設或停止會話

若要暫時停止工作階段,您可以叫用 Stop()。 這樣做會停止任何監看員和環境處理,即使您叫用 ProcessFrame()。 然後,您可以叫 Start() 用 以繼續處理。 繼續時,會維護會話中已擷取的環境數據。

深入瞭解 Stop 方法。

    this.cloudSession.Stop();

若要重設工作階段中擷取的環境數據,您可以叫用 Reset()

深入瞭解 Reset 方法。

    this.cloudSession.Reset();

若要在工作階段之後正確清除,請叫用 Dispose()

深入瞭解 Dispose 方法。

    this.cloudSession.Dispose();

下一步

在本指南中,您已瞭解如何使用 Azure Spatial Anchors SDK 建立和尋找錨點。 若要深入瞭解錨點關聯性,請繼續進行下一個指南。