core-egret.lifecycle.globalFunction⚡

egret.lifecycle.globalFunction 使用範例, Tween 動畫有問題


class Main extends eui.UILayer {

    protected createChildren(): void {
        super.createChildren();

        // egret.lifecycle 用於管理 egret 生命週期
        console.log('egret.lifecycle.contexts.length', egret.lifecycle.contexts.length); // 1, 表示系統預設有一個 LifecycleContext

        egret.lifecycle.addLifecycleListener((context: egret.lifecycle.LifecycleContext) => {
            // 客製化 Lifecycle
            window.onblur = () => {context.pause(),console.log('onblur pause')}; // 滑鼠點擊示窗外, 觸發 egret.lifecycle.onPause
            window.onfocus = () => {context.resume(),console.log('onfocus resume')}; // 滑鼠點擊示窗內,  觸發 egret.lifecycle.onResume
        })

        console.log('egret.lifecycle.contexts.length', egret.lifecycle.contexts.length); // 2, addLifecycleListener 會新增一個 LifecycleContext, 本處設置客製化內容

        // 設置心跳開關 (下面兩行可以註解試試)
        egret.lifecycle.onPause = () => egret.ticker.pause();
        egret.lifecycle.onResume = () => egret.ticker.resume();

        egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
        egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
        this.runGame();
    }

    private async loadResource() {
        let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
        await RES.loadConfig('resource/default.res.json', 'resource/');
        await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
        await RES.loadGroup('preload', 0, loadingView);
        this.stage.removeChild(loadingView);
    }

    private async runGame() {
        await this.loadResource();
        // --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---

        // 動畫, 受 egret.ticker pause 跟 resume 影響
        
        // enterframe 動畫, 物件 x 從 0 到 200 反覆播放
        const s = new egret.Shape;
        s.graphics.beginFill(0xFF0000);
        s.graphics.drawRect(0, 0, 100, 100);
        s.graphics.endFill();
        this.addChild(s);
        this.addEventListener(eui.UIEvent.ENTER_FRAME,()=>{
            s.x+=10;
            if(s.x > 200) s.x = 0;
        },this);

        // 設置 Tween 為循環動畫, 物件一秒內 x 從 0 到 200
        const s2 = new egret.Shape;
        s2.graphics.beginFill(0x00FF00);
        s2.graphics.drawRect(0, 0, 100, 100);
        s2.graphics.endFill();
        s2.y = 100;
        this.addChild(s2);
        egret.Tween.get(s2, { loop: true }).set({ x: 0 }).to({ x: 200 }, 1000);

        // 結論. enterframe 動畫 跟 Tween 動畫兩者都會受 pause 跟 resume 影響
        // 但是 enterframe 動畫能從暫停點回復動畫, 而 Tween 動畫會亂跳
        // Tween 動畫雖簡單易用, 卻有此問題. 尋求高手解答 :)

    }

}

spacer

沒有留言:

張貼留言