cocos2d-html5学习笔记(四)--键盘事件和touch事件

游戏是互动的,获取用户输入至关重要。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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值