需求描述:
给sprite增加touch监听
解决方案
local CardSprite = class("CardSprite",function()
return display.newSprite()
end)
function CardSprite:ctor()
self:openTouch()
end
--支持触摸事件
function CardSprite:openTouch()
local x = 0;
local y = 0;
local function onMyTouchBegan( touch,event )
local pos = touch:getLocation()
x = pos.x
y = pos.y
return true
end
local function onMyTouchEnded(touch,event)
local pos = touch:getLocation();
local rx = pos.x
local ry = pos.y
local rrx = rx - x
local rry = ry - y
if math.abs(rrx) >= math.abs(rry) then
if rrx>0 then
print("右移动")
elseif rrx < 0 then
print("左移动")
else
print("一动不动")
end
else
if rry > 0 then
print("上移动")
elseif rry < 0 then
print("下移动")
end
end
end
local touchListen = cc.EventListenerTouchOneByOne:create()
touchListen:registerScriptHandler(onMyTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN)
touchListen:registerScriptHandler(onMyTouchEnded,cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(touchListen,self)
end
return CardSprite
效果: