(1)新建类TouchLayer
local TouchLayer=class("TouchLayer", function()
return display.newNode()
end)
function TouchLayer:ctor(params)
-- self._func = params.func
player = params
self:init()
end
function TouchLayer:init()
-- body
local colorLayer=display.newColorLayer(ccc4(23,222,21,0))
self:addChild(colorLayer, 0)
-- 触摸事件
colorLayer:setTouchSwallowEnabled(true)
colorLayer:setTouchEnabled(true)
colorLayer:setTouchMode(cc.TOUCH_MODE_ONE_BY_ONE)
--cc.TOUCH_MODE_ALL_AT_ONCE 是多点触摸
--注册触摸事件
colorLayer:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event)
if event.name == "began" then
print("beganMask")
return true
elseif event.name == "moved" then
local x1 = event.x
print(x1)
local y1 = event.y
local x2 = event.prevX
local y2 = event.prevY
print(x2)
local x = x1 - x2
local y = y1 - y2
if player:getPositionX() + x > 33 and player:getPositionX() + x < 287 and player:getPositionY() + y > 40 and player:getPositionY() + y < 440 then
player:setPosition(ccp(player:getPositionX() + x, player:getPositionY() + y))
end
print("movedMask")
elseif event.name == "ended" then
print("endedMask")
return true
end
return false
end)
end
return TouchLayer
(2)在另一个类中调用
local touchlayer=TouchLayer.new(player)-------》player移动
self:addChild(touchlayer)