Egret学习-坦克大战开发(四)

现在给坦克加入发射子弹功能

1.创建一个子弹类,子弹不使用图片,直接egret.Shape画出一个小圆形

子弹应该有移动功能,很简单,按照原有方向移动

 1 class Bullet extends egret.DisplayObjectContainer {
 2 
 3     dir: string;
 4     tank: Tank;
 5 
 6     public constructor() {
 7         super();
 8         this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
 9     }
10 
11     private onAddToStage(event: egret.Event) {
12         var shp:egret.Shape = new egret.Shape();
13         shp.graphics.beginFill( 0xffff00, 1);
14         shp.graphics.drawCircle(0, 0, 5);
15         shp.graphics.endFill();
16         this.addChild(shp);
17     }
18 
19     // 移动
20     public move() {
21         if(this.dir == 'up') {
22             this.y -= 1;
23         }
24 
25         if(this.dir == 'down') {
26             this.y += 1;
27         }
28 
29         if(this.dir == 'left') {
30             this.x -= 1;
31         }
32 
33         if(this.dir == 'right') {
34             this.x += 1;
35         }
36     }
37     
38 }

2.给坦克加入创建子弹和发射子弹方法

 1 // 发射子弹
 2     public shoot() {
 3         let bullet = this.createBullet();
 4         this.parent.addChild(bullet);
 5         Main.bulletList.push(bullet);
 6     }
 7 
 8     // 创建子弹
 9     public createBullet() {
10         let obj:Bullet = new Bullet();
11         obj.tank = this;
12         obj.dir = this.dir;
13 
14         if(this.dir == 'up') {
15             obj.x = this.x;
16             obj.y = this.y - 20;
17         }
18 
19         if(this.dir == 'down') {
20             obj.x = this.x;
21             obj.y = this.y + 20;
22         }
23 
24         if(this.dir == 'left') {
25             obj.x = this.x - 20;
26             obj.y = this.y;
27         }
28 
29         if(this.dir == 'right') {
30             obj.x = this.x + 20;
31             obj.y = this.y;
32         }
33         
34         return obj;
35     }

3.坦克点击时,发射子弹

 1     private onAddToStage() {
 2         this.img = new egret.Bitmap();
 3         this.img.texture = RES.getRes(this.name_prefix + '_' + this.dir + '_png');
 4         this.addChild(this.img);
 5 
 6         this.touchEnabled = true;
 7         this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTankTouch, this);
 8     }
 9 
10     // 坦克被点击
11     private onTankTouch(e) {
12         this.shoot();
13     }

 

你可能感兴趣的:(Egret学习-坦克大战开发(四))