Nanfeng

Notes on software development, code, and curious ideas

Physics Collision Detection in Cocos2d-x Lua

Cocos2d-x 3.x integrates a physics world with scenes and nodes. A PhysicsBody belongs to a node, while contact events are delivered through EventListenerPhysicsContact.

Create a physics scene

1
2
3
4
local scene = cc.Scene:createWithPhysics()
local world = scene:getPhysicsWorld()
world:setGravity(cc.p(0, -980))
world:setDebugDrawMask(cc.PhysicsWorld.DEBUGDRAW_ALL)

Disable debug drawing in production.

Add a boundary body to a node:

1
2
3
4
5
6
7
8
9
local edge = cc.PhysicsBody:createEdgeBox(
cc.size(display.width, display.height),
cc.PhysicsMaterial(0.1, 1.0, 0.0),
3
)
local boundary = cc.Node:create()
boundary:setPosition(display.cx, display.cy)
boundary:setPhysicsBody(edge)
scene:addChild(boundary)

Create a dynamic sprite:

1
2
3
4
5
6
7
8
local ball = cc.Sprite:create("ball.png")
local body = cc.PhysicsBody:createCircle(ball:getContentSize().width / 2)
body:setDynamic(true)
body:setCategoryBitmask(0x01)
body:setCollisionBitmask(0x02)
body:setContactTestBitmask(0x02)
ball:setPhysicsBody(body)
scene:addChild(ball)

Listen for contacts

1
2
3
4
5
6
7
8
9
local listener = cc.EventListenerPhysicsContact:create()
listener:registerScriptHandler(function(contact)
local shapeA = contact:getShapeA()
local shapeB = contact:getShapeB()
print("contact began", shapeA, shapeB)
return true
end, cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN)

scene:getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, scene)

The category mask identifies what a body is. The collision mask determines which categories produce physical collision response, and the contact-test mask determines which interactions produce callbacks. A pair is considered according to both bodies’ masks, so define named bit constants instead of unexplained hexadecimal values.

Contact callbacks run during the physics step. Avoid immediately removing bodies or restructuring the scene in ways the engine version cannot safely handle; queue destructive game actions for the next update when necessary.

+