Egret学习笔记 (Egret打飞机-6.实现敌机飞起来)

有了子弹,总得有敌人来打吧,不然游戏有啥意思呢?今天我们来实现敌机从屏幕上边往下飞

参考微信打飞机游戏里面,敌机分为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();

飞机就从屏幕的左上角往下飞了。。。。。

有点卡顿是我截图的问题。。。。实际是很流畅的

posted on 2018-01-05 15:35  快乐海盗  阅读(1468)  评论(0编辑  收藏  举报