移动精灵
这一步,我们需要让飞机跟着我们的手指移动。不用担心,这其实非常简单。
当我们的手指触摸到游戏屏幕的时候,引擎将会调用Layer的几个回调函数,分别是:
1.onTouchesBegan(touches,event):当手指刚触摸屏幕时调用
2.onTouchesMoved(touches,event):当手指在屏幕上移动时调用
3.onTouchesEnded(touches,event):当手指停止触摸时调用
我们要做的就是设置一个标志,当手指触摸时,将这个标志设置为true。当手离开时将这个标志设置为false。当手指移动时判断,如果标志为true,则将飞机设置到触摸点的位置。这样,就实现了飞机随着手指的移动而移动了。
还有一点需要注意的:只有将Layer设置为可触摸的,才会接受触摸时间。
var MyLayer = cc.LayerColor.extend({
plane:null,
init:function () {
// 1. super init first
// 必须调用父类init()方法,很多bug都是由于没有调用父类init()方法造成的
this._super();
// 设置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);
// 将层设置为可触摸
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;
}
}
});
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=187994
下一篇:http://www.cocoachina.com/bbs/read.php?tid=188218
