游戏是互动的,获取用户输入至关重要。cocos2d中目前只有Layer以及其子类默认能够获取用户输入,即触发用户输入的事件。其他节点需要开启触摸事件的话,需要自己手动实现。
现在看一个例子:
var Green=cc.Layer.extend({
init:function () {
var layer1=cc.LayerColor.create(cc.c4(0,255,0,255),320,480);
this.addChild(layer1);
this.setKeyboardEnabled(true);
this.setTouchEnabled(true);
return true;
},
onKeyUp:function (key) {
window.alert(key);
},
onKeyDown:function (key) {
window.alert(key);
},
onTouchesEnded:function (touches,event) {
alert(touches[0].locationInView().x);
}
});
在绿色层左边点击一下,效果如图:
至于可以有哪些事件,自己可以查看API文档的cc.KeypadDelegate和cc.StandardTouchDelegate。
至于其他节点,比如Sprite,需要手动实现,主要用到的方法是:cc.Director.getInstance().getTouchDispatcher().addStandardDelegate()和cc.Director.getInstance().getTouchDispatcher().removeDelegate。一下是我的一个实现。
var CanTouchSprite=cc.Sprite.extend({
_touchBegan:false,
_touchEnabled:true,
ctor:function(){
this._super();
},
onEnter:function(){
cc.Director.getInstance().getTouchDispatcher().addStandardDelegate(this, 0);
this._touchEnabled=true;
this._super();
},
onExit:function(){
cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);
this._touchEnabled=false;
this._super();
},
touchRect:function(){
return this.getBoundingBoxToWorld();
},
setTouchEnabled:function(enable){
if(enable&&!this._touchEnabled){
cc.Director.getInstance().getTouchDispatcher().addStandardDelegate(this, 0);
this._touchEnabled=true;
}
else if(!enable&&this._touchEnabled){
cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);
this._touchEnabled=false;
}
},
onTouchesBegan:function(touches,event){
if(cc.Rect.CCRectContainsPoint(this.touchRect(),touches[0].getLocation())){
this._touchBegan=true;
}
},
onTouchesMoved:function(touches,event){
},
onTouchesEnded:function(touches,event){
if(this._touchBegan){
this._touchBegan=false;
}
}
})