定义两个全局变量
var bLeftButtonClick = false; var bRightButtonClick = false; var MainLayer = cc.Layer.extend({
监听事件
var sprite1 = cc.Sprite.create(res.btn_left_up); sprite1.setPosition(size.width/2 - 80, size.height/2 + 80); this.addChild(sprite1, 10); var sprite2 = cc.Sprite.create(res.btn_right_up); sprite2.setPosition(size.width/2, size.height/2); this.addChild(sprite2, 20); // Make sprite1 touchable var listener1 = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, //TOUCH_ONE_BY_ONE 为单次触摸事件监听器 swallowTouches: true, onTouchBegan: function (touch, event) { var target = event.getCurrentTarget(); var locationInNode = target.convertToNodeSpace(touch.getLocation()); var s = target.getContentSize(); var rect = cc.rect(0, 0, s.width, s.height); if (cc.rectContainsPoint(rect, locationInNode)) { if (target == sprite2) { bRightButtonClick = true; } else if (target == sprite1) { bLeftButtonClick = true; } // 需要返回true,否则不会调用后面的onTouchEnded方法 return true; } return false; }, onTouchEnded: function (touch, event) { var target = event.getCurrentTarget(); if (target == sprite2) { bRightButtonClick = false; } else if (target == sprite1) { bLeftButtonClick = false; } } }); cc.eventManager.addListener(listener1, sprite1); cc.eventManager.addListener(listener1.clone(), sprite2);
在每帧刷新事件里面处理
// 定时任务 update:function (dt) { this._ball.update(dt); this.checkIsCollide(); if (bLeftButtonClick) { this._man.runLeft(dt); } else if (bRightButtonClick) { this._man.runRight(dt); } },