cocos2d-html5教程之-键盘事件和touch事件
来源:互联网 发布:vb打印九九乘法表 编辑:程序博客网 时间:2024/05/18 18:55
cocos2d-html5教程之-键盘事件和touch事件
转载自http://blog.csdn.net/allenice1/article/details/7733340
游戏是互动的,获取用户输入至关重要。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;
- }
- }
- })
0 0
- cocos2d-html5教程之-键盘事件和touch事件
- cocos2d-html5学习笔记(四)--键盘事件和touch事件
- cocos2d-html5学习笔记(四)--键盘事件和touch事件
- cocos2d-html5学习笔记(四)--键盘事件和touch事件
- Cocos2d-html5 touch事件总结
- Cocos2D-X 之 Touch事件
- Cocos2d-x之Touch事件
- 手机网站(html5)之touch事件
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- cocos2d-x 3.0 之 Touch事件
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- Cocos2d-x之Touch事件处理机制
- cocos2d学习-Touch事件
- 举例讲解JAVA中的堆和栈
- ReplaceText
- 黑马程序员_Java基础[22]_异常总结
- 大端序和小端序
- 希尔排序
- cocos2d-html5教程之-键盘事件和touch事件
- 比float更好的网页布局之inline-block
- 第九周项目三-分数类
- Java核心API
- HDOJ 3487 Play with Chain
- cocos2d-x js binding 防止触摸事件传递 - sslin
- 中医3个不花钱的养肾方
- maven中央仓库地址
- TeX Live 2010 安装步骤(ubuntu 10.10下测试通过)