1.创建多个sprite,并为每个sprite添加点击事件监听器并且实现回调。
代码如下:
-- 创建物品icon,id:物品ID,name:显示的数量 function Country_Icon.create(id,name) local rootLayer = ccui.Layout:create(); local bgImg ="image/i5 (1).png"; local icon = cc.Sprite:createWithSpriteFrameName(bgImg); if icon then rootLayer:addChild(icon); icon:setPositionX(50); icon:setPositionY(50); icon:setAnchorPoint(cc.p(0.5,0.5)); icon:setName("icon"); end --创建触摸事件 local listener = cc.EventListenerTouchOneByOne:create(); --注册触摸结束事件 listener:registerScriptHandler( function(touch,event) return true; end,cc.Handler.EVENT_TOUCH_BEGAN ); listener:registerScriptHandler( function(touch,event) local target = event:getCurrentTarget(); local name = target:getName(); local name2 = rootLayer:getName(); if target == icon then icon:runAction(action.btnAction(function(a,b) cclog("callback"); end)); end return true; end,cc.Handler.EVENT_TOUCH_ENDED ); --添加注册触摸事件到分配器 cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener,icon) return rootLayer; end
如图所示:当屏幕任意地方点击事件发生的时候,所有图标都会变为半透明,显然不是我想要的效果。(所有的sprite都监听到了点击事件)。
所以这时候我们需要用到参数touch,进行区域判断,EVENT_TOUCH_BEGAN 部分代码修改如下:
listener:registerScriptHandler( function(touch,event) local target = event:getCurrentTarget(); local locationInNode = target:convertToNodeSpace(touch:getLocation()); local s = target:getContentSize(); local rect = cc.rect(0,s.width,s.height); -- 点击范围判断检测 if (cc.rectContainsPoint(rect,locationInNode)) then --target:setOpacity(180); return true; end return false; end,cc.Handler.EVENT_TOUCH_BEGAN );
这样效果就实现了。
注意:点击事件监听的时候需要用到区域判断。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|