cocos2d 事件

事件监听器分为:

1.EventListenerTouch(触摸事件)

2.EventListenerKeyboard(键盘事件)

3.EventListenerMouse(鼠标响应事件)

3.EventListenerAcceleration(加速记录事件)

4.EventListenerCustom(自定义事件)

事件分发器:cc.Director:getInstance():getEventDispatcher()

Cocos2d-x中的事件处理者是事件监听类EventListener,它的子类主要有:

EventListenerTouchOneByOne(单点触摸监听器) 
EventListenerTouchAllAtOnce(多点触摸监听器) 
EventListenerKeyBoard(键盘事件监听器) 
EventListenerMouse(鼠标事件监听器) 
EventListenerAcceleration(加速度事件监听器) 
EventListenerCustom(自定义事件监听器)

触摸事件:

   local start_ = nil
     local function onTouchBegan(touch, event)
        self.canClick = true
        if not start_ then
           start_ =  touch:getLocation()
        end
         return true --可以执行后面的 moved cancelled ended
     end
     local function onTouchMoved(touch, event)
        local touchLocation = touch:getLocation()
         if self.start_  then
            --如果滑动距离超过10px,则点击事件取消
            if cc.pGetDistance(touchLocation, self.start_) > 10 then
                self.canClick = false
            end
        end
     end
     local function onTouchCancelled(touch, event)
         if self.canClick then
             --触摸逻辑处理
         end
     end
     local function onTouchEnded(touch, event)
         
     end

     local listener_touch = cc.EventListenerTouchOneByOne:create()
     listener_touch:setSwallowTouches(true)  --不可向下传递 
     listener_touch:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN)
     listener_touch:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED)
     listener_touch:registerScriptHandler(onTouchCancelled,cc.Handler.EVENT_TOUCH_CANCELLED)
     listener_touch:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED)
     local eventDispatcher = self:getEventDispatcher() --事件派发器  
      
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener_touch, self) --分发监听事

cc.Handler.EVENT 查看文件 Cocos2dConstants.lua

或者使用 cocos2dx lua封装的方法:

local scene = self:getResourceNode()

 	local  button = scene:getChildByName("Button_1")
    button:setTag(100)
 	local function menuZhuCeCallback(sender,eventType)
        print(sender:getTag())
        if eventType == ccui.TouchEventType.began then
            print("按下按钮")
        elseif eventType == ccui.TouchEventType.moved then --已经实现移出绑定的目标不会执行ended方法
            print("按下按钮移动")
        elseif eventType == ccui.TouchEventType.ended then
            print("放开按钮")
        elseif eventType == ccui.TouchEventType.canceled then
            print("取消点击")
        end
	end 

 	button:addTouchEventListener(menuZhuCeCallback)

消息自定义事件:点击打开链接


你可能感兴趣的:(cocos2d)