cocos2d-x-lua 单点触摸事件

时间:2023-02-09 13:56:46

示例代码:

    local player = cc.Sprite:create(fileName)
player:runAction(self:flyaction())


--touch move
-- player:setTouchEnabled(true) -- "setTouchEnabled" is not use In cocos2d-x3.3,改为直接在onTouchBegan里判断,如果返回false,不能被触摸


function onTouchBegan(pTouch,pEvent)
local point = pTouch:getLocation()
local rect = player:getBoundingBox()
if (cc.rectContainsPoint(rect,point)) then
return true;
end

return false;
end

function onTouchEnded(pTouch,pEvent)

end

function onTouchMoved(touch, event)

local posX,posY = player:getPosition() --获取当前的位置
local delta = touch:getDelta() --获取滑动的距离
player:setPosition(cc.p(posX + delta.x, posY + delta.y)) --给精灵重新设置位置
end

local listener1 = cc.EventListenerTouchOneByOne:create() --创建一个单点事件监听
listener1:setSwallowTouches(true) --是否向下传递
--注册三个回调监听方法
listener1:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )

listener1:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )

listener1:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )

local eventDispatcher = player:getEventDispatcher() --事件派发器

eventDispatcher:addEventListenerWithSceneGraphPriority(listener1, player) --分发监听事

注意在场景退出的时候移除监听:

function Syplayer:onExit()
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:removeEventListener(self.listener1)

self:cleanup()
end

cocos2d-x 3.x Lua 中事件监听:

有3中touch的方式,分别和cocos2dx里的三种对应:

onTouchBegan    cc.Handler.EVENT_TOUCH_BEGAN

onTouchMoved    cc.Handler.EVENT_TOUCH_MOVED

onTouchEnded    cc.Handler.EVENT_TOUCH_ENDED

要实现touch的相关动作:存在一个监听器listen

1.创建监听器listen;2.注册;3.事件派发给谁;4.添加到分发器中