首先设置整体场景的物体世界
self =display.newScene("MainScene",{physics=true})--创建物体世界
local physicsWord = self:getPhysicsWorld()
physicsWord:setGravity(cc.p(0, 0))
physicsWord:setUpdateRate(3);--设置频率
if physicsWord ~=nil then
physicsWord:setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)
end
local function onContactBegin(contact)--碰撞后的回调
local a = contact:getShapeA():getBody()
local bulletNode =nil
local b = contact:getShapeB():getBody()
local fishNode = nil
local bulletIsMe= 0
if a:getTag()>=0 then
bulletNode =a:getNode();
bulletIsMe=a:getTag();
fishNode = b:getNode();
else
bulletNode =b:getNode();
bulletIsMe=b:getTag();
fishNode = a:getNode();
end
if bulletNode~=nil and fishNode~=nil then
self.eventDispatcher = self:getEventDispatcher()
if(bulletIsMe>0) then
local event = cc.EventCustom:new(EventMsgId.MSG_FISH_HIT)
event.data =
{fishID=fishNode:getTag(),bulletID=bulletNode:getTag(),isMe=bulletIsMe}
self.eventDispatcher:dispatchEvent(event)
end
end
return true
end
local contactListener = cc.EventListenerPhysicsContact:create()--设置碰撞回调
contactListener:registerScriptHandler(onContactBegin,
cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(contactListener, self)
然后,设置碰撞物体的body设置
物体1:
self._body =cc.PhysicsBody:createBox(cc.size(60.0, 60))
self._body:setCategoryBitmask(1) -- 0001掩码
self._body:setContactTestBitmask(2) -- 0011消息
self._body:setCollisionBitmask(0) -- 0010碰撞
self._body:setTag(1)
self.m_pArmature:setPhysicsBody(self._body);
物体2:
self._bodySprite:setScale(_sx, _sy)
self._bodySprite:setPosition(-1000,-1000)
self._bodySprite:setRotation(_fishRotate)
self._bodySprite:setTag(self.uid)
_mainUILayer:addChild(self._bodySprite)