Table of Contents

AR Session 流程控制

這篇文檔將介紹 AR Session 流程控制,包括如何創建、啓動、停止並銷燬 AR Session。

開始之前

創建

使用配置中的雲定位庫 appId,雲服務 serverAddress,雲服務 apiKeyapiSecret 創建 APIKeyAccessData

然後使用創建的 APIKeyAccessData 創建 MegaTrackerConfigs

再使用 MegaTrackerConfigs 和配置中的 licenseKey 創建 SessionConfigs

最終用 xr-frame 場景中掛載的 EasyARMegaComponentcreateSession(sessionConfigs) 方法創建 session。

createSession() {
    // 獲取場景中掛載的 megaComponent
    const megaElement = scene.getElementById('easyar-mega');
    const megaComponent = megaElement.getComponent("easyar-mega") as easyar.EasyARMegaComponent;
    // MegaTracker 雲服務鑑權配置
    const apiKeyAccess = new mega.APIKeyAccessData(this.data.appId, this.data.serverAddress, this.data.apiKey, this.data.apiSecret);
    const megaTrackerConfigs: easyar.MegaTrackerConfigs = {
        access: apiKeyAccess
    }
    // Session 配置
    const sessionConfigs: easyar.SessionConfigs = {
        megaTrackerConfigs: megaTrackerConfigs,
        licenseKey: settings.EasyARLicenseKey
    }
    // 創建實例
    session = megaComponent.createSession(sessionConfigs);
}

這段代碼演示瞭如何從場景中獲取 megaComponent 之後使用配置創建 session 實例。

注意

單實例限制:一個場景中僅允許存在一個 Session 實例。在創建新 Session 前,必須確保已調用 closeSession() 銷燬舊實例,否則將導致創建失敗。

啓動

一般在 xr-frame 的 AR 系統準備就緒的回調中使用 EasyARSessionstart(options) 方法啓動 session。

警告

MegaTracker 依賴於平面 AR 追蹤器提供的數據,在平面追蹤器初始化完成前無法工作。

在 WXML 中使用 bind:ready="handleReady" 註冊 AR 系統準備就緒事件:

<xr-scene ar-system="modes:Plane; planeMode: 1" bind:ready="handleReady">

在 xr-frame 組件中的回調函數 handleReady 中使用 EasyARSessionstart(options) 方法啓動 session。

handleReady: function(event) {
    try {
        //啓動 Session,默認失敗重試 5 次
        await session.start();
    } catch (err) {
        console.error(`EasyAR Session initialization failed: ${err.message}`);
        return;
    }
}

停止並銷燬

使用 xr-frame 場景中掛載的 EasyARMegaComponentcloseSession() 方法銷燬 session。

建議在 xr-frame 組件生命週期的 detached 中調用保證在離開頁面時(即組件實例被從頁面節點樹移除時)銷燬。

lifetimes: {
    detached: function() {
        const megaElement = scene.getElementById('easyar-mega');
        const megaComponent = megaElement.getComponent("easyar-mega") as easyar.EasyARMegaComponent;
        megaComponent.closeSession();
    }
}

前後臺切換

在頁面退到後臺時使用 EasyARSessionpause() 方法暫停 session。 在頁面回到前臺時使用 EasyARSessionresume() 方法恢復 session。

/** 小程序頁面的調用*/
onHide() {
    if (this.ar) {
        this.ar.pauseSession();
    }
},
onShow() {
    if (this.ar) {
        this.ar.resumeSession();
    }
}
/** xr-frame 組件中的函數*/
pauseSession(): void {
    if (!session) { console.error("EasyAR Session is not ready"); return;}
    session.pause();
},
resumeSession(): void {
    if (!session) { console.error("EasyAR Session is not ready"); return;}
    session.resume();
}

這段代碼中 xr-frame 組件暴露了 pauseSession()resumeSession() 兩個函數。

在小程序頁面中在 onHide 即小程序從前臺進入後臺時調用 pauseSession() 暫停 session。

onShow 即小程序從後臺進入前臺時調用 resumeSession() 恢復 session。