发射子弹
光有飞机未免太无聊了,这一步我们就实现飞机发射子弹。
添加子弹和添加飞机类似,只是为子弹增加了动作,使之能够向上移动,看起来就像飞机发射的一样。
那怎么让飞机隔一段时间就能发射一枚子弹呢?这就需要为Layer设定定时器。让Layer每隔一段时间就执行一次添加子弹。
var MyLayer = cc.LayerColor.extend({
plane:null,
_bullets:null,
init:function () {
// 1. super init first
// 必须调用父类init()方法,很多bug都是由于没有调用父类init()方法造成的
this._super();
// 用来装子弹的数组
this._bullets = ];
// 设置Layer的背景
this.setColor(cc.c4(126,126,126,126));
// 获得游戏可视的尺寸
var winSize = cc.Director.getInstance().getWinSize();
// 获取屏幕坐标原点
var origin = cc.Director.getInstance().getVisibleOrigin();
// 创建一个飞机,游戏中大部分物体都能使用cc.Sprite表示
// 飞机的图案按照cc.rect(x,y,width,height)从图片中截取
// 以(x,y)为左上角,width为宽,height为高的矩形
this.plane = cc.Sprite.create(s_Plane,cc.rect(2,168,62,75));
// 将飞机设置在屏幕底部,居中的位置
// 图片的锚点在矩形的中心点,设置的就是这个点的位置
this.plane.setPosition(cc.p(origin.x + winSize.width/2 , origin.y + this.plane.getContentSize().height/2));
this.addChild(this.plane,1);
// 设置定时器,定时器每隔0.2秒调用一次addBullet方法
this.schedule(this.addBullet,0.2);
// 将层设置为可触摸
this.setTouchEnabled(true);
return true;
},
onTouchesMoved:function(touches,event){
var touch = touches;
var location = touch.getLocation();
if(this.onClickFlag){
this.plane.setPosition(location);
}
},
onTouchesEnded:function(touches, event){
this.onClickFlag = false;
},
onTouchesBegan:function(touches,event){
var touch = touches;
var location = touch.getLocation();
if(cc.rectContainsPoint(this.plane.getBoundingBox(),location)){
this.onClickFlag = true;
}
},
addBullet:function(){
var winSize = cc.Director.getInstance().getWinSize();
var origin = cc.Director.getInstance().getVisibleOrigin();
// 获得飞机的位置
var planePosition = this.plane.getPosition();
// 子弹穿越屏幕要花费的秒数
var bulletDuration = 1;
// 创建一个子弹
var bullet = cc.Sprite.create(s_Plane,cc.rect(66,237,7,20));
// 根据飞机的位置,初始化子弹的位置
bullet.setPosition(cc.p(planePosition.x,planePosition.y+bullet.getContentSize().height));
// 一个移动的动作
// 第一个参数为移动到目标所需要花费的秒数,为了保持速度不变,需要按移动的距离与屏幕高度按比例计算出花费的秒数
var actionMove = cc.MoveTo.create(bulletDuration * ((winSize.height - planePosition.y - bullet.getContentSize().height/2)/winSize.height),
cc.p(planePosition.x,
origin.y + winSize.height + bullet.getContentSize().height/2));
// 设置一个回调函数,移动完毕后回调spriteMoveFinished()方法。
var actionMoveDone = cc.CallFunc.create(this.spriteMoveFinished,this);
// 让子弹执行动作
bullet.runAction(cc.Sequence.create(actionMove,actionMoveDone));
// 为子弹设置标签,以后可以根据这个标签判断是否这个元素为子弹
bullet.setTag(6);
this._bullets.push(bullet);
this.addChild(bullet,0);
},
spriteMoveFinished:function(sprite){
// 将元素移除出Layer
this.removeChild(sprite, true);
if(sprite.getTag()==6){
// 把子弹从数组中移除
var index = this._bullets.indexOf(sprite);
if (index > -1) {
this._bullets.splice(index, 1);
}
}
}
});
var MyScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new MyLayer();
this.addChild(layer);
layer.init();
}
});
```
效果图如下:
上一篇:http://www.cocoachina.com/bbs/read.php?tid=188216
下一篇:http://www.cocoachina.com/bbs/read.php?tid=188220
