代码如下。。。
MainScene.lua
local MainScene = class("MainScene", function()
return display.newPhysicsScene("MainScene")
end)
MainScene.coinSprite = nil
MainScene.contactListener = nil
function MainScene:ctor()
-- create touch layer
self.layer = display.newLayer()
self.layer:setTouchEnabled(true)
self.layer:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event)
return self:onTouch(event.name, event.x, event.y)
end)
self:addChild(self.layer)
self.world = self:getPhysicsWorld()
self.world:setGravity(cc.p(0, 0))
-- add debug node
self.world:setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)
-- add sprite
self:createCoin(300,300,1)
self.coinSprite = self:createCoin(100,100,2)
--监听物理碰撞
local onContactBegin = function(event)
print("MainScene----------碰撞到了")
end
self.contactListener = cc.EventListenerPhysicsContact:create()
self.contactListener:registerScriptHandler(onContactBegin, cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
local eventDispathcher = cc.Director:getInstance():getEventDispatcher()
eventDispathcher:addEventListenerWithFixedPriority(self.contactListener, 1)
end
--创建要碰撞的对象
function MainScene:createCoin(x, y,testBitMask)
local coinSprite = display.newSprite("#Coin.png")
self:addChild(coinSprite)
local boxBody = cc.PhysicsBody:createBox(cc.size(100,100))
boxBody:setCollisionBitmask(testBitMask)
boxBody:setContactTestBitmask(testBitMask)
coinSprite:setPhysicsBody(boxBody)
coinSprite:getPhysicsBody():setCategoryBitmask(2);
coinSprite:setPosition(x, y)
return coinSprite
end
function MainScene:onTouch(event, x, y)
if event == "began" then
self.coinSprite:setPosition(x,y)
end
end
return MainScene
求大神们帮忙看看什么问题导致碰撞检测事件无法调用到,真不知道怎么回事,参考了论坛里面好几个帖子的说法,都没有试成功。。。。
