本文代码适用于Cocos2d-x Quick-Community3.6
local TestScene = class("TestScene", function()
return display.newScene("TestScene")
end)
function TestScene:ctor()
end
function TestScene:onEnter()
self:initUI()
end
function TestScene:initUI()
--刮刮卡底层容器
local scratchLayer = display.newLayer()
scratchLayer:setContentSize(self:getBoundingBox())
self:addChild(scratchLayer)
scratchLayer:setTouchEnabled(true)
scratchLayer:setTouchMode(cc.TOUCH_MODE_ONE_BY_ONE)
--创建RenderTexture
local scratch = cc.RenderTexture:create(scratchLayer:getBoundingBox().width,scratchLayer:getBoundingBox().height)
scratch:setPosition(scratchLayer:getBoundingBox().width/2,scratchLayer:getBoundingBox().height/2)
scratch:retain()
--需要被挂掉的精灵 本文以纯白背景代替
local bg = cc.Sprite:createWithTexture(nil, cc.rect(0,0 , scratchLayer:getBoundingBox().width,scratchLayer:getBoundingBox().height))
bg:setColor(cc.c3b(255,255,255))
bg:setPosition(scratchLayer:getBoundingBox().width/2,scratchLayer:getBoundingBox().height/2)
--渲染
scratch:begin()
bg:visit()
scratch:endToLua()
scratchLayer:addChild(scratch)
--利用DrawNode创建模拟的刮除媒介
local eraser = cc.DrawNode:create()
--刮除媒介是个圆 半径为20 具体可自行定义
local r = 20
eraser:drawSolidCircle(cc.p(0,0),
r,
0,
r,
1,
1,
cc.c4f(0,0,0,0)
)
eraser:retain()
--开始添加触摸事件
scratchLayer:addNodeEventListener(cc.NODE_TOUCH_EVENT, function (event)
--首先把点击区域刮除
eraser:setPosition(event.x,event.y)
eraser:setBlendFunc(gl.ONE,gl.ZERO)
scratch:begin()
eraser:visit()
--[[
重点:因为点击事件回调次数限制,如果没有下面处理,
当我们快速在屏幕上滑动的时候调用次数不够,会产生一个一个刮除点
而中间并没有刮除。
以下代码为刮除两次移动中间矩形区域
]]
local isEnded = false
if event.name ~= "began" then
if eraser.lastPos then
--矩形宽高
local width = self:getP2PDis(event, eraser.lastPos)
local height = 2*r
--矩形中点
local midPos = cc.p((event.x+eraser.lastPos.x)/2,(event.y+eraser.lastPos.y)/2)
--旋转角度
local rotate = self:getP2PAngle(eraser.lastPos, event)
--矩形刮除媒介
local polygonEraser = cc.DrawNode:create()
local points = {
cc.p(-width/2,-height/2),
cc.p(-width/2,height/2),
cc.p(width/2,height/2),
cc.p(width/2,-height/2)
}
polygonEraser:drawPolygon(points, {
fillColor = cc.c4f(0, 0, 0, 0),
borderWidth = 1,
borderColor = cc.c4f(0, 0, 0, 0),
})
--刮除矩形区域
polygonEraser:setRotation(-rotate)
polygonEraser:setPosition(midPos)
polygonEraser:setBlendFunc(gl.ONE,gl.ZERO)
polygonEraser:visit()
scratch:endToLua()
isEnded = true
end
end
if not isEnded then
scratch:endToLua()
end
eraser.lastPos = cc.p(event.x,event.y)
if event.name == "ended" then
eraser.lastPos = nil
end
return true
end)
end
--两点间距
function TestScene:getP2PDis(p1,p2)
local x = p1.x - p2.x
local y = p1.y - p2.y
return math.abs(math.sqrt(math.pow(x,2)+math.pow(y,2)))
end
--两点连接线倾斜角度
function TestScene:getP2PAngle(p1,p2)
local x = p1.x - p2.x
local y = p1.y - p2.y
return 180 * (math.atan2(y, x) / math.pi)
end
return TestScene