在较早的版本如3.0beta使用如下代码的话:
-- add ground
local groudNode = cc.Node:create()
groudNode:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(0, landHeight), cc.p(288, landHeight)))
layer:addChild(groudNode)
-- add bird
local spriteBird = createBird()
spriteBird:setPhysicsBody(cc.PhysicsBody:createCircle(birdSize))
layerBg:addChild(spriteBird)
local function onContactBegin(contact)
print("onContactBegin")
return true;
end
-- bind contact listenser
local contactListener = cc.EventListenerPhysicsContactWithBodies:create(groudNode:getPhysicsBody(), spriteBird:getPhysicsBody())
contactListener:registerScriptHandler(onContactBegin, cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
layer:getEventDispatcher():addEventListenerWithSceneGraphPriority(contactListener, layer)注册给事件 cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN 的回调函数是会被调用的,然后到了3.0版本后,以上的代码便无法正常工作,cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN事件并未被触发,需要额外为以上代码中的2个刚体对象groudNode:getPhysicsBody()和spriteBird:getPhysicsBody()分别调用setContactTestBitmask(mask),其中mask取同一个值从而使得2个刚体对象属于同一个Contact测试组,这样才能保证当2个刚体接触时Contact事件能被触发,进而调用回调函数。
正确的示例代码如下:
-- add ground
local groudNode = cc.Node:create()
groudNode:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(0, landHeight), cc.p(288, landHeight)))
groudNode:getPhysicsBody():setContactTestBitmask(1);
layer:addChild(groudNode)
-- add bird
local spriteBird = createBird()
spriteBird:setPhysicsBody(cc.PhysicsBody:createCircle(birdSize))
spriteBird:getPhysicsBody():setContactTestBitmask(1);
layerBg:addChild(spriteBird)
local function onContactBegin(contact)
print("onContactBegin")
return true;
end
-- bind contact listenser
local contactListener = cc.EventListenerPhysicsContactWithBodies:create(groudNode:getPhysicsBody(), spriteBird:getPhysicsBody())
contactListener:registerScriptHandler(onContactBegin, cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
layer:getEventDispatcher():addEventListenerWithSceneGraphPriority(contactListener, layer)
在Cocos2d-x 3.0版本中,遇到响应物理引擎的Contact事件回调不执行的问题。在早期版本中,通过注册cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN回调可以工作,但3.0版本后不再有效。解决方法是为涉及的刚体对象设置contactTestBitmask,确保它们属于同一Contact测试组,这样在刚体接触时,事件回调才会被正确触发。
6285

被折叠的 条评论
为什么被折叠?



