egret.DisplayObject 註冊事件範例
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 給你最乾淨的程式碼, 從這行以下開始寫喔 ---
// 添加自定義顯示物件
this.addChild(new DisplayObjectExample);
}
}
// egret.Shape 繼承自 egret.DisplayObject, 所以有 egret.DisplayObject 相關屬性方法
// 本範例 DisplayObjectExample 繼承自 egret.Shape, 所以也有 egret.DisplayObject 相關屬性方法
// 因為 egret.DisplayObject 本身無法顯示, 所以用 egret.Shape graphics 繪製畫面跟使用者交互
class DisplayObjectExample extends egret.Shape {
public constructor() {
super();
// eui 組件預設都是開啟, 其他繼承自 egret.DisplayObject 都是關閉, 這是與用戶交互的開關
this.touchEnabled = true;
// 繪製 100 x 100 紅色方塊
this.draw();
// 當自身 addChild 加入場景時觸發, 而 egret.Event.ADDED 是除自身有子元件加入時也會觸發
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAdded, this);
// 註冊每次進入影格更新事件(會跟著影格速率連續執行)
this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
// 當自身 removeChild 從場景移除時觸發, 而 egret.Event.REMOVED 是除自身有子元件移除時也會觸發
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemoved, this);
// 當手指或滑鼠點擊自身時觸發
this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick, this);
// 每當顯示清單(父容器)結構異動時(添加子物件或移除子物件時)觸發
this.addEventListener(egret.Event.RENDER, this.onRender, this);
}
private draw(): void {
this.graphics.beginFill(0xff0000);
this.graphics.drawRect(0, 0, 100, 100);
this.graphics.endFill();
}
private onClick(event: MouseEvent): void {
egret.log("onClick");
this.parent.removeChild(this);
}
private onAdded(event: Event): void {
egret.log("onAdded");
}
private onEnterFrame(event: Event): void {
egret.log("onEnterFrame");
this.removeEventListener("enterFrame", this.onEnterFrame, this);
}
private onRemoved(event: Event): void {
egret.log("onRemoved");
}
private onRender(event: Event): void {
egret.log("onRender");
}
}
沒有留言:
張貼留言