首先按照一般步骤创建物理世界,然后注册碰撞事件侦听器如下:
local contactListener = cc.EventListenerPhysicsContact:create() contactListener:registerScriptHandler(function(contact) print("contactBegin","-----------",type(contact)) return true end,cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN) contactListener:registerScriptHandler(function(contact,solve) print("contactPresolve",type(contact),type(solve)) return true end,cc.Handler.EVENT_PHYSICS_CONTACT_PRESOLVE) contactListener:registerScriptHandler(function(contact,solve) print("contactPostsolve",type(solve)) end,cc.Handler.EVENT_PHYSICS_CONTACT_POSTSOLVE) contactListener:registerScriptHandler(function(contact) print("contactSeperate",type(contact)) end,cc.Handler.EVENT_PHYSICS_CONTACT_SEPERATE) self:getEventDispatcher():addEventListenerWithFixedPriority(contactListener,1)随后在设置想要侦听碰撞事件的刚体类型。
/** * A mask that defines which categories this physics body belongs to. * Every physics body in a scene can be assigned to up to 32 different categories,each corresponding to a bit in the bit mask. You define the mask values used in your game. In conjunction with the collisionBitMask and contactTestBitMask properties,you define which physics bodies interact with each other and when your game is notified of these interactions. * The default value is 0xFFFFFFFF (all bits set). */ void setCategoryBitmask(int bitmask); /** * A mask that defines which categories of bodies cause intersection notifications with this physics body. * When two bodies share the same space,each body’s category mask is tested against the other body’s contact mask by performing a logical AND operation. If either comparison results in a non-zero value,an PhysicsContact object is created and passed to the physics world’s delegate. For best performance,only set bits in the contacts mask for interactions you are interested in. * The default value is 0x00000000 (all bits cleared). */ void setContactTestBitmask(int bitmask); /** * A mask that defines which categories of physics bodies can collide with this physics body. * When two physics bodies contact each other,a collision may occur. This body’s collision mask is compared to the other body’s category mask by performing a logical AND operation. If the result is a non-zero value,then this body is affected by the collision. Each body independently chooses whether it wants to be affected by the other body. For example,you might use this to avoid collision calculations that would make negligible changes to a body’s velocity. * The default value is 0xFFFFFFFF (all bits set). */ void setCollisionBitmask(int bitmask);
CategoryBitmask与CollisionBitmask决定是否发生碰撞。
注意,默认是不发送碰撞事件,且均可发生碰撞的。
原文链接:/cocos2dx/344488.html