有了子彈,總得有敵人來打吧,不然游戲有啥意思呢?今天我們來實現敵機從屏幕上邊往下飛
參考微信打飛機游戲里面,敵機分為3種 1是特小飛機,2是小飛機,還有一種就是大飛機
面向對象編程提倡抽象,實現代碼復用的目的。所以我們打算把飛機的相同的點都抽象到飛機基類里面。
新建一個文件EnemyPlane.ts,敵機類,以后我們所有的飛機,都從這個類來擴展
class EnemyPlane extends egret.DisplayObjectContainer {
_enemy: egret.Bitmap;
_timer: egret.Timer;
_speed: number = 2;
_tyle: EnemyType = EnemyType.SMALL;
/**
* 是否使用
*/
public IsUse: boolean = false;
_main: Main;
public constructor(main: Main, type: EnemyType) {
super();
this._main = main;
this._tyle = type;
this._enemy = new egret.Bitmap();
this.addChild(this._enemy);
this.addEventListener(egret.Event.ADDED_TO_STAGE, () => {
}, this)
}
/**
* 使用
*/
public Use() {
this.IsUse = true;
//判斷類型
this.y = -this.height; //初始化飛機的位置為屏幕外
this._main.addChildAt(this, 10)
this.addEventListener(egret.Event.ENTER_FRAME, this.frame, this)
}
/**
* 回收
*/
public Recycle() {
console.log("敵機回收-----")
this.IsUse = false;
this._main.removeChild(this);
this.removeEventListener(egret.Event.ENTER_FRAME, this.frame, this)
}
frame() {
console.log("EnemyPlane Frame")
if (this.IsUse) {
this.y += this._speed;
if (this.y >= GameConfig.SceneH) {
//從父節點中移除
if (this.parent) {
this.parent.removeChild(this);
this.Recycle();
}
}
}
}
}
/**
* 敵機類型
*/
enum EnemyType {
/**
* 大飛機
*/
BIG = 1,
/**
* 小飛機
*/
SMALL = 0,
/**
* 特別小的飛機
*/
VERSCHWINDENDSMALL = 2
}
在基類的構造方法中,我們初始化一些基本的對象,入飛機的Bitmap等等
在基類中,目前就三個方法對我們比較重要。Use方法,初始化當前飛機的Y坐標的位置,並監聽ENTER_FRAME事件,Recycle方法是還原當前飛機的狀態,並移除飛機的ENTER_FRAME事件,frame方法主要是移動飛機位置,並且在飛機飛出屏幕外面的時候,從父容器中移除當前飛機,並調用飛機的Recycle方法回收飛機
基類定義的方法,以后每個飛機都要用到,比如實現小飛機,大飛機,都可以從基類中擴展,復用基類已經實現的方法
基類實現好了,我們開始擴展具體的飛機,本篇隨便只會擴展一種,其他的大家有興趣自己去擴展
新建一個SmallEnemyPlane.ts的文件。
class SmallEnemyPlane extends EnemyPlane {
public constructor(main: Main) {
super(main, EnemyType.SMALL);
this.width = 69;
this.height = 89;
this._enemy.texture = RES.getRes("enemy2_png");
this.addEventListener(egret.Event.ADDED_TO_STAGE, () => {
}, this)
}
}
在小飛機類里面,給父類構造方法傳遞一個自己的飛機類型進去,然后根據圖片的寬高,設置自己的寬高。並加載圖片。
到這里,飛機的的方法就全部實現完畢了,把這個對象添加到Main里面
var small = new SmallEnemyPlane(this)
small.Use();
飛機就從屏幕的左上角往下飛了。。。。。
有點卡頓是我截圖的問題。。。。實際是很流暢的