`
zhouxi2010
  • 浏览: 50070 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

cocos2d-html5教程之-键盘事件和touch事件

阅读更多

转载自http://blog.csdn.net/allenice1/article/details/7733340

游戏是互动的,获取用户输入至关重要。cocos2d中目前只有Layer以及其子类默认能够获取用户输入,即触发用户输入的事件。其他节点需要开启触摸事件的话,需要自己手动实现。

现在看一个例子:

 

[javascript] view plaincopy
 
  1. var Green=cc.Layer.extend({  
  2.       
  3.     init:function  () {  
  4.         var layer1=cc.LayerColor.create(cc.c4(0,255,0,255),320,480);  
  5.   
  6.         this.addChild(layer1);  
  7.         this.setKeyboardEnabled(true);  
  8.         this.setTouchEnabled(true);  
  9.   
  10.         return true;  
  11.     },  
  12.   
  13.     onKeyUp:function (key) {  
  14.         window.alert(key);  
  15.     },  
  16.   
  17.     onKeyDown:function (key) {  
  18.         window.alert(key);  
  19.     },  
  20.   
  21.     onTouchesEnded:function (touches,event) {  
  22.         alert(touches[0].locationInView().x);  
  23.     }  
  24. });  

 

在绿色层左边点击一下,效果如图:

至于可以有哪些事件,自己可以查看API文档的cc.KeypadDelegate和cc.StandardTouchDelegate。

至于其他节点,比如Sprite,需要手动实现,主要用到的方法是:cc.Director.getInstance().getTouchDispatcher().addStandardDelegate()和cc.Director.getInstance().getTouchDispatcher().removeDelegate。一下是我的一个实现。

 

[javascript] view plaincopy
 
  1. var CanTouchSprite=cc.Sprite.extend({  
  2.     _touchBegan:false,  
  3.     _touchEnabled:true,  
  4.     ctor:function(){  
  5.         this._super();  
  6.     },  
  7.     onEnter:function(){  
  8.         cc.Director.getInstance().getTouchDispatcher().addStandardDelegate(this, 0);  
  9.         this._touchEnabled=true;  
  10.         this._super();  
  11.     },  
  12.     onExit:function(){  
  13.         cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);  
  14.         this._touchEnabled=false;  
  15.         this._super();  
  16.     },  
  17.     touchRect:function(){  
  18.         return this.getBoundingBoxToWorld();  
  19.     },  
  20.     setTouchEnabled:function(enable){  
  21.         if(enable&&!this._touchEnabled){  
  22.             cc.Director.getInstance().getTouchDispatcher().addStandardDelegate(this, 0);  
  23.             this._touchEnabled=true;  
  24.         }  
  25.         else if(!enable&&this._touchEnabled){  
  26.             cc.Director.getInstance().getTouchDispatcher().removeDelegate(this);  
  27.             this._touchEnabled=false;  
  28.         }  
  29.     },  
  30.     onTouchesBegan:function(touches,event){  
  31.         if(cc.Rect.CCRectContainsPoint(this.touchRect(),touches[0].getLocation())){  
  32.             this._touchBegan=true;  
  33.         }  
  34.     },  
  35.     onTouchesMoved:function(touches,event){  
  36.   
  37.     },  
  38.     onTouchesEnded:function(touches,event){  
  39.         if(this._touchBegan){  
  40.             this._touchBegan=false;  
  41.         }  
  42.     }  
  43. })  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics