本文實例為大家分享了Cocos2d實現刮刮卡效果展示的具體代碼,供大家參考,具體內容如下
本文代碼適用于Cocos2d-x Quick-Community3.6
local TestScene = class("TestScene", function() return display.newScene("TestScene")end)function TestScene:ctor() endfunction TestScene:onEnter() self:initUI()endfunction 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)endreturn TestScene
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答