app.js中的实现:
1 var HelloWorldLayer = cc.Layer.extend({ 2 3 defualt:null, 4 5 ctor:function () { 6 7 this._super(); 8 mainscene = ccs.load(res.MainScene_json).node; 9 this.addChild(mainscene); 10 11 var sprite1 = ccui.helper.seekWidgetByName(mainscene,"sprite1"); 12 var sprite2 = ccui.helper.seekWidgetByName(mainscene,"sprite2"); 13 var sprite3 = ccui.helper.seekWidgetByName(mainscene,"sprite3"); 14 15 var self = this; 16 var listener1 = cc.EventListener.create({ 17 event: cc.EventListener.TOUCH_ONE_BY_ONE, 18 swallowTouches: true, // 设置是否吞没事件,在 onTouchBegan 方法返回 true 时吞掉事件,不再向下传递。 19 onTouchBegan: function (touch, event) { //实现 onTouchBegan 事件处理回调函数 20 var target = event.getCurrentTarget(); // 获取事件所绑定的 target, 通常是cc.Node及其子类 21 // 获取当前触摸点相对于按钮所在的坐标 22 var locationInNode = target.convertToNodeSpace(touch.getLocation()); 23 var s = target.getContentSize(); 24 var rect = cc.rect(0, 0, s.width, s.height); 25 26 if (cc.rectContainsPoint(rect, locationInNode)) { // 判断触摸点是否在按钮范围内 27 cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y); 28 target.opacity = 180; 29 if(self.defualt){ // 接受触摸的精灵显示在最上层 30 if(self.defualt != target){ 31 target.setLocalZOrder(100); 32 self.defualt.setLocalZOrder(0); 33 self.defualt = target; 34 } 35 }else{ 36 target.setLocalZOrder(100); 37 self.defualt = target; 38 } 39 return true; 40 } 41 return false; 42 }, 43 onTouchMoved: function (touch, event) { //实现onTouchMoved事件处理回调函数, 触摸移动时触发 44 // 移动当前按钮精灵的坐标位置 45 var target = event.getCurrentTarget(); 46 var delta = touch.getDelta(); //获取事件数据: delta 47 target.x += delta.x; 48 target.y += delta.y; 49 }, 50 onTouchEnded: function (touch, event) { // 实现onTouchEnded事件处理回调函数 51 var target = event.getCurrentTarget(); 52 cc.log("sprite onTouchesEnded.. "); 53 target.setOpacity(255); 54 } 55 }); 56 57 cc.eventManager.addListener(listener1, sprite1); 58 cc.eventManager.addListener(listener1.clone(), sprite2);//此处需要使用clone(),否则只注册了sprite1的监听 59 cc.eventManager.addListener(listener1.clone(), sprite3); 60 61 return true; 62 }, 63 }); 64 65 66 var HelloWorldScene = cc.Scene.extend({ 67 onEnter:function () { 68 this._super(); 69 var layer = new HelloWorldLayer(); 70 this.addChild(layer); 71 } 72 });