core-egret.Point

egret.Point 飛機子彈生成銷毀範例


class Main extends eui.UILayer {

    protected createChildren(): void {
        super.createChildren();
        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 給你最乾淨的程式碼, 從這行以下開始寫喔 ---

        // 這個範例主要講解 localToGlobal 坐標系轉換用法, localToGlobal 取得的座標即 egret.Point

        const stage = egret.MainContext.instance.stage;
        // 創建飛機居中於舞台
        const img = new eui.Image('bg_jpg');
        img.x = stage.stageWidth / 2 - img.width / 2;
        img.y = stage.stageHeight / 2 - img.height / 2;
        img.width = 100;
        img.height = 100;
        this.addChild(img);
        // 滑鼠點擊即產生子彈
        this.addEventListener(egret.TouchEvent.TOUCH_TAP,()=>this.bulletCreate(img),this);

    }

    // 子彈創建, owner 為子彈創建在什麼對象上
    private bulletCreate(owner: egret.DisplayObject) {
        const bullet = new eui.Rect;
        bullet.width = 10;
        bullet.height = 10;
        const bulletStartMovePoint: egret.Point = owner.localToGlobal(owner.width / 2, 0); // 將飛機坐標系的指定坐標轉成場景座標
        bullet.x = bulletStartMovePoint.x - bullet.width / 2;
        bullet.y = bulletStartMovePoint.y - bullet.height / 2;
        bullet.addEventListener(eui.UIEvent.ENTER_FRAME, this.bulletMove, this);
        this.addChild(bullet);
    }

    // 子彈移動動畫
    private bulletMove(e: egret.Event) {
        const bullet = e.target;
        // 子彈超出場景刪除
        if (bullet.y < 0) {
            this.removeChild(bullet);
            // arguments.callee 就是 bulletMove 函式
            bullet.removeEventListener(eui.UIEvent.ENTER_FRAME, arguments.callee, this);
            return;
        }
        // 子彈移動
        bullet.y -= 20;
    };

}

spacer

沒有留言:

張貼留言