Skip to main content

coloX Box2D (b2d) Lua Binding Guide

Lua API for a Box2D-based 2D physics engine, using objects and factory functions.

Enabling the Module​

Enable the b2d module with usemod('b2d'):

usemod('b2d')

Core Concepts​

  • World — Physics world managing all physics objects, simulation steps, and collision detection
  • Body — Rigid body with physical properties such as position, velocity, and mass
  • Fixture — Attached to a Body, defining shape, density, friction, and other collision properties
  • Joint — Connects two Bodies and constrains their relative motion
  • Contact — Represents a collision between two Fixtures

Coordinates and Units​

The b2d module uses pixels (points) as its uniform external coordinate unit. The meter parameter when creating a World specifies pixels per meter; conversion between Box2D meters and pixels is automatic. All Lua coordinates, velocities, forces, and related parameters are passed and returned in pixel units.

local meter = 16  -- 1 meter = 16 pixels
local world = b2d.newWorld(0, 10, true, meter)

Contents​

  1. Global functions and constants
  2. World
  3. Body
  4. Fixture
  5. Joint
  6. Contact
  7. JointEdge and ContactEdge
  8. Complete API index
  9. Complete examples

1. Global Functions and Constants​

Constants​

ConstantValueDescription
b2d.staticBody0Static body—does not move or respond to forces
b2d.kinematicBody1Kinematic body—moves through assigned velocity, unaffected by forces
b2d.dynamicBody2Dynamic body—fully participates in physics simulation

Factory Functions​

FunctionDescription
b2d.newWorld(gx?, gy?, sleep?, meter?)Create a physics world → world

Parameters:

  • gx — Gravity X component, default 0
  • gy — Gravity Y component, default 0 (positive points downward)
  • sleep — Allow sleeping optimization, default true
  • meter — Pixels per meter, default 1
local world = b2d.newWorld(0, 10, true, 16)

2. World​

world:createBody(def) -> body​

Creates a body. def is a table supporting:

FieldTypeDescription
typeintBody type: 0=static, 1=kinematic, 2=dynamic
position{x,y}Initial position (pixels)
anglenumberInitial angle (radians)
linearVelocity{x,y}Initial linear velocity
angularVelocitynumberInitial angular velocity
linearDampingnumberLinear damping
angularDampingnumberAngular damping
allowSleepboolAllow sleeping
awakeboolInitially awake
fixedRotationboolFix rotation
bulletboolEnable CCD continuous collision detection
activeboolActive state
gravityScalenumberGravity scale factor
local ground = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 10 * meter}
})

local box = world:createBody({
type = b2d.dynamicBody,
position = {x = 4 * meter, y = 5 * meter}
})

world:createJoint(def) -> joint​

Creates a joint. def must contain type (joint type enum), bodyA, and bodyB; remaining fields vary by joint type. See Joint creation parameters.

world:destroyBody(body)​

Destroys a body and all its Fixtures and Joints.

world:destroyJoint(joint)​

Destroys a joint.

world:step(dt, velocityIterations?, positionIterations?)​

Steps the physics simulation.

  • dt — Time step (seconds)
  • velocityIterations — Velocity solver iteration count, default 8
  • positionIterations — Position solver iteration count, default 3
world:step(1/30, 6, 2)

world:stepWithContact(dt, velocityIterations?, positionIterations?, contactTable?) -> contactTable​

Steps the simulation and collects collision information into a table. Each entry is:

{isTouching, bodyA, bodyB, fixtureA, fixtureB}
local contacts = world:stepWithContact(1/30, 6, 2, {})

world:drawDebugData(flags?)​

Draws debug graphics. flags is a bitmask, default 0xffffffff (draw everything).

world:drawDebugData(0x13)  -- Draw only shapes and joints

Other World Methods​

MethodDescription
world:setGravity(gx, gy)Set gravity
world:getGravity()Return gx, gy
world:setAllowSleeping(bool)Set whether sleeping is allowed
world:getAllowSleeping()Return whether sleeping is allowed
world:getBodyCount()Return body count
world:getJointCount()Return joint count
world:getContactCount()Return contact count
world:getBodyList()Return body list head
world:getJointList()Return joint list head
world:getContactList()Return contact list head
world:queryAABB(lx, ly, hx, hy, resultTable?)Query Fixtures within an AABB, each entry {body, fixture}
world:rayCast(callback, p1x, p1y, p2x, p2y)Ray cast

3. Body​

Creating Fixtures​

body:createFixture(def) -> fixture​

Creates a fixture on the body. def supports:

FieldTypeDescription
densitynumberDensity
frictionnumberFriction coefficient
restitutionnumberRestitution coefficient
isSensorboolSensor (detects collisions without a physical response)
filtertableCollision filter: {categoryBits, maskBits, groupIndex}
shapetableShape definition (below)

Shape Definitions​

The shape subtable must contain type, matching the Box2D shape type enum:

typeShapeAdditional fields
0circlep={x,y} (center), radius
1edgevertex1={x,y}, vertex2={x,y}, optional vertex0, vertex3 (ghost vertices)
2polygonMethod 1: hx, hy, optional center, angle for a rectangle; method 2: vertices (array of 3~8 {x,y} vertices)
3chainvertex (array of {x,y}), optional loop (bool, closed)
-- Rectangular fixture
body:createFixture({
density = 1,
friction = 0.3,
restitution = 1,
shape = {type = 2, hx = 0.1 * meter, hy = 0.1 * meter}
})

Position and Motion​

MethodDescription
body:getPosition()Return x, y (pixels)
body:getX()Return x (pixels)
body:getY()Return y (pixels)
body:getAngle()Return angle (radians)
body:setPosition(x, y)Set position (pixels)
body:setX(x)Set x
body:setY(y)Set y
body:setAngle(angle)Set angle
body:setTransform(x, y, angle)Set position and angle together
body:getLinearVelocity()Return vx, vy (pixels/second)
body:setLinearVelocity(vx, vy)Set linear velocity
body:getAngularVelocity()Return angular velocity (radians/second)
body:setAngularVelocity(omega)Set angular velocity

Forces and Impulses​

MethodDescription
body:applyForce(fx, fy, wake?)Apply force at the center of mass
body:applyForce(fx, fy, rx, ry, wake?)Apply force at (rx,ry)
body:applyImpulse(jx, jy, wake?)Apply impulse at the center of mass
body:applyImpulse(jx, jy, rx, ry, wake?)Apply impulse at a specified point
body:applyTorque(torque, wake?)Apply torque

wake defaults to false; set it to true to wake the body.

body:applyForce(0, -1, true)  -- Apply an upward force and wake the body

Mass Properties​

MethodDescription
body:getMass()Return mass
body:getInertia()Return rotational inertia
body:getWorldCenter()Return world center-of-mass coordinates x, y
body:getLocalCenter()Return local center-of-mass coordinates x, y
body:resetMassData()Recalculate mass from Fixtures
body:setMassData(mass?, cx?, cy?, inertia?)Set mass properties (all parameters optional)
body:setInertia(inertia)Set rotational inertia (preserving mass and center of mass)

Coordinate Transforms​

MethodDescription
body:getWorldPoint(lx, ly)Local → world coordinates (returns x, y)
body:getWorldVector(lx, ly)Local → world vector
body:getLocalPoint(wx, wy)World → local coordinates
body:getLocalVector(wx, wy)World → local vector
body:getLinearVelocityFromWorldPoint(wx, wy)Linear velocity at a world point
body:getLinearVelocityFromLocalPoint(lx, ly)Linear velocity at a local point

Setting and Querying Properties​

MethodDescription
body:setType(type)Set body type
body:getType()Return body type
body:setBullet(bool)Set CCD flag
body:isBullet()Return CCD flag
body:setActive(bool)Activate/deactivate
body:isActive()Return active state
body:setAwake(bool)Wake/sleep
body:isAwake()Return awake state
body:setSleepingAllowed(bool)Set whether sleeping is allowed
body:isSleepingAllowed()Return whether sleeping is allowed
body:setFixedRotation(bool)Set fixed rotation
body:isFixedRotation()Return fixed rotation flag
body:setGravityScale(scale)Set gravity scale
body:getGravityScale()Return gravity scale
body:setLinearDamping(d)Set linear damping
body:getLinearDamping()Return linear damping
body:setAngularDamping(d)Set angular damping
body:getAngularDamping()Return angular damping

User Data and Traversal​

MethodDescription
body:setUserData(value)Set user data (any Lua value; nil clears it)
body:getUserData()Return user data
body:getNext()Return next body in the list
body:getNextUD()Return next body's user data
body:destroyFixture(fixture)Destroy specified fixture

Collision and Joint Traversal​

MethodDescription
body:hasTouching()Whether any collisions are currently touching
body:scanTouching(callback)Traverse contacts, callback(bodyA_ud, bodyB_ud, fixtureA_ud, fixtureB_ud); truthy return stops traversal
body:hasJoint()Whether joints exist
body:getContactList()Return contactedge list head
body:getJointList()Return jointedge list head

4. Fixture​

Setting and Querying Properties​

MethodDescription
fixture:getType()Return shape type
fixture:getBody()Return owning body
fixture:getBodyUD()Return owning body's user data
fixture:setDensity(d)Set density
fixture:getDensity()Return density
fixture:setFriction(f)Set friction coefficient
fixture:getFriction()Return friction coefficient
fixture:setRestitution(r)Set restitution coefficient
fixture:getRestitution()Return restitution coefficient
fixture:setSensor(bool)Set sensor flag
fixture:isSensor()Return sensor flag
fixture:testPoint(x, y)Test whether a point is inside the shape

Collision Filtering​

MethodDescription
fixture:setFilterData(categoryBits?, maskBits?, groupIndex?)Set filter data
fixture:setFilterCategory(bits)Set only categoryBits
fixture:setFilterMask(bits)Set only maskBits
fixture:setFilterGroup(index)Set only groupIndex
fixture:getFilterData()Return categoryBits, maskBits, groupIndex
fixture:getFilterGroup()Return groupIndex

Mass and Bounding Boxes​

MethodDescription
fixture:getMass()Return mass
fixture:getMassData()Return mass, cx, cy, inertia
fixture:getAABB(childIndex?)Return lx, ly, hx, hy (bounding box, pixels); childIndex defaults to 0

User Data and Traversal​

MethodDescription
fixture:setUserData(value)Set user data
fixture:getUserData()Return user data
fixture:getNext()Return next fixture in the list

5. Joint​

Joint Creation Parameters​

Fields shared by all joints: bodyA, bodyB, collideConnected (bool, allow collisions between connected bodies).

Revolute Joint​

A joint rotating around a fixed point.

FieldDescription
anchorAnchor {x,y} (localAnchor computed automatically)
localAnchorALocal anchor on bodyA
localAnchorBLocal anchor on bodyB
referenceAngleReference angle
enableLimitEnable angular limits
lowerAngleLower angle limit
upperAngleUpper angle limit
enableMotorEnable motor
motorSpeedMotor speed
maxMotorTorqueMaximum motor torque

Prismatic Joint​

A joint translating along an axis.

FieldDescription
localAnchorA, localAnchorBLocal anchors
localAxisALocal axis direction
referenceAngleReference angle
enableLimitEnable translation limits
lowerTranslationLower limit
upperTranslationUpper limit
enableMotorEnable motor
motorSpeedMotor speed
maxMotorForceMaximum motor force

Distance Joint​

Maintains a fixed distance between two anchors.

FieldDescription
localAnchorA, localAnchorBLocal anchors
lengthLength (computed automatically if ≤0)
frequencyHzSpring frequency
dampingRatioDamping ratio

Pulley Joint​

Simulates a pulley connecting two Bodies by ropes.

FieldDescription
localAnchorA, localAnchorBLocal anchors
groundAnchorA, groundAnchorBGround anchors
lengthA, lengthBRope lengths
ratioPulley ratio

Mouse Joint​

Drags a body with the mouse.

FieldDescription
targetTarget point {x,y}
maxForceMaximum force
frequencyHzSpring frequency
dampingRatioDamping ratio

Gear Joint​

FieldDescription
ratioGear ratio

Wheel Joint​

A wheel with a spring.

FieldDescription
localAnchorA, localAnchorBLocal anchors
localAxisALocal axis direction
enableMotorEnable motor
maxMotorTorqueMaximum motor torque
motorSpeedMotor speed
frequencyHzSpring frequency
dampingRatioDamping ratio

Weld Joint​

Welds two bodies together.

FieldDescription
localAnchorA, localAnchorBLocal anchors
referenceAngleReference angle
frequencyHzSpring frequency
dampingRatioDamping ratio

Friction Joint​

FieldDescription
localAnchorA, localAnchorBLocal anchors
maxForceMaximum force
maxTorqueMaximum torque

Rope Joint​

FieldDescription
localAnchorA, localAnchorBLocal anchors
maxLengthMaximum length

Common Joint Methods​

MethodDescription
joint:getType()Return joint type
joint:getBodyA()Return bodyA
joint:getBodyB()Return bodyB
joint:getBodyAB()Return bodyA, bodyB
joint:getAnchorA()Return world coordinates x, y of anchor A
joint:getAnchorB()Return world coordinates x, y of anchor B
joint:getAnchorAB()Return ax, ay, bx, by
joint:getReactionForce(inv_dt)Return reaction force fx, fy
joint:getReactionTorque(inv_dt)Return reaction torque
joint:isActive()Return active state
joint:setUserData(value)Set user data
joint:getUserData()Return user data
joint:getNext()Return next joint in the list

Joint Type-Specific Methods​

DistanceJoint​

MethodDescription
joint:getLength()Return current length
joint:setLength(len)Set length
joint:getFrequency()Return spring frequency
joint:setFrequency(hz)Set spring frequency
joint:getDampingRatio()Return damping ratio
joint:setDampingRatio(ratio)Set damping ratio

RevoluteJoint​

MethodDescription
joint:getJointAngle()Return current joint angle
joint:getJointSpeed()Return joint speed
joint:isLimitEnabled()Whether limits are enabled
joint:enableLimit(bool)Enable/disable limits
joint:getLowerLimit()Return lower limit
joint:getUpperLimit()Return upper limit
joint:setLimits(lower, upper)Set limit range
joint:isMotorEnabled()Whether motor is enabled
joint:enableMotor(bool)Enable/disable motor
joint:setMotorSpeed(speed)Set motor speed
joint:getMotorSpeed()Return motor speed
joint:setMaxMotorTorque(torque)Set maximum motor torque
joint:getMaxMotorTorque()Return maximum motor torque
joint:getMotorTorque(inv_dt)Return current motor torque
joint:getReferenceAngle()Return reference angle

PrismaticJoint​

MethodDescription
joint:getJointSpeed()Return joint speed
joint:isLimitEnabled()Whether limits are enabled
joint:enableLimit(bool)Enable/disable limits
joint:getLowerLimit()Return lower limit
joint:getUpperLimit()Return upper limit
joint:setLimits(lower, upper)Set limit range
joint:isMotorEnabled()Whether motor is enabled
joint:enableMotor(bool)Enable/disable motor
joint:setMotorSpeed(speed)Set motor speed
joint:getMotorSpeed()Return motor speed
joint:setMaxMotorForce(force)Set maximum motor force
joint:getReferenceAngle()Return reference angle

MouseJoint​

MethodDescription
joint:setTarget(tx, ty)Set target point
joint:getTarget()Return target point tx, ty
joint:setMaxForce(force)Set maximum force
joint:getMaxForce()Return maximum force
joint:getFrequency()Return spring frequency
joint:setFrequency(hz)Set spring frequency
joint:getDampingRatio()Return damping ratio
joint:setDampingRatio(ratio)Set damping ratio

WheelJoint​

MethodDescription
joint:getJointSpeed()Return joint speed
joint:isMotorEnabled()Whether motor is enabled
joint:enableMotor(bool)Enable/disable motor
joint:setMotorSpeed(speed)Set motor speed
joint:getMotorSpeed()Return motor speed
joint:setMaxMotorTorque(torque)Set maximum motor torque
joint:getMaxMotorTorque()Return maximum motor torque
joint:getMotorTorque(inv_dt)Return current motor torque

WeldJoint​

MethodDescription
joint:getReferenceAngle()Return reference angle
joint:getFrequency()Return spring frequency
joint:setFrequency(hz)Set spring frequency
joint:getDampingRatio()Return damping ratio
joint:setDampingRatio(ratio)Set damping ratio

FrictionJoint​

MethodDescription
joint:setMaxForce(force)Set maximum force
joint:getMaxForce()Return maximum force

6. Contact​

MethodDescription
contact:isTouching()Whether currently touching
contact:setEnabled(bool)Enable/disable this contact
contact:isEnabled()Return enabled state
contact:getFixtureA()Return fixtureA
contact:getFixtureB()Return fixtureB
contact:getFixtureAB()Return fixtureA, fixtureB
contact:getFixtureABodyUD()Return bodyA_ud, fixtureA_ud
contact:getFixtureBBodyUD()Return bodyB_ud, fixtureB_ud
contact:getFixtureABBodyUD()Return bodyA_ud, fixtureA_ud, bodyB_ud, fixtureB_ud
contact:getChildIndexA()Return fixtureA child index
contact:getChildIndexB()Return fixtureB child index
contact:getNext()Return next contact in the list
contact:setFriction(f)Override contact friction coefficient
contact:getFriction()Return friction coefficient
contact:resetFriction()Reset to the default calculated value
contact:setRestitution(r)Override contact restitution coefficient
contact:getRestitution()Return restitution coefficient
contact:resetRestitution()Reset to the default calculated value

7. JointEdge and ContactEdge​

JointEdge​

Body joint list nodes, used to traverse all joints on a Body.

MethodDescription
jointedge:getJoint()Return joint object
jointedge:getJointUD()Return joint user data
jointedge:getBodyB()Return the other body
jointedge:getBodyBUD()Return the other body's user data
jointedge:getNext()Return next jointedge

ContactEdge​

Body contact list nodes, used to traverse all contacts on a Body.

MethodDescription
contactedge:getContact()Return contact object
contactedge:getBodyB()Return the other body
contactedge:getBodyBUD()Return the other body's user data
contactedge:getNext()Return next contactedge

8. Complete API Index​

Globals​

Function/constantDescription
b2d.newWorld(gx?, gy?, sleep?, meter?)Create a physics world → world
b2d.staticBody0 Static body
b2d.kinematicBody1 Kinematic body
b2d.dynamicBody2 Dynamic body

World Methods​

MethodDescription
world:createBody(def)Create body → body
world:createJoint(def)Create joint → joint
world:destroyBody(body)Destroy body
world:destroyJoint(joint)Destroy joint
world:step(dt, vel?, pos?)Step simulation
world:stepWithContact(dt, vel?, pos?, tbl?)Step and collect collisions
world:drawDebugData(flags?)Draw debug graphics
world:setGravity(gx, gy)Set gravity
world:getGravity()Return gx, gy
world:setAllowSleeping(bool)Set sleeping
world:getAllowSleeping()Return sleeping flag
world:getBodyCount()Body count
world:getJointCount()Joint count
world:getContactCount()Contact count
world:getBodyList()Body list head
world:getJointList()Joint list head
world:getContactList()Contact list head
world:queryAABB(lx, ly, hx, hy, tbl?)AABB query
world:rayCast(cb, p1x, p1y, p2x, p2y)Ray cast

Body Methods​

MethodDescription
body:createFixture(def)Create fixture → fixture
body:destroyFixture(fixture)Destroy fixture
body:getPosition()Position → x, y
body:getX()Position x
body:getY()Position y
body:getAngle()Angle
body:setPosition(x, y)Set position
body:setX(x)Set x
body:setY(y)Set y
body:setAngle(angle)Set angle
body:setTransform(x, y, angle)Set position + angle
body:getLinearVelocity()Linear velocity → vx, vy
body:setLinearVelocity(vx, vy)Set linear velocity
body:getAngularVelocity()Angular velocity
body:setAngularVelocity(omega)Set angular velocity
body:applyForce(fx, fy, wake?)Apply force (center of mass)
body:applyForce(fx, fy, rx, ry, wake?)Apply force (specified point)
body:applyImpulse(jx, jy, wake?)Apply impulse (center of mass)
body:applyImpulse(jx, jy, rx, ry, wake?)Apply impulse (specified point)
body:applyTorque(torque, wake?)Apply torque
body:getMass()Mass
body:getInertia()Rotational inertia
body:getWorldCenter()World center of mass → x, y
body:getLocalCenter()Local center of mass → x, y
body:resetMassData()Recalculate mass
body:setMassData(m?, cx?, cy?, inertia?)Set mass properties
body:setInertia(inertia)Set rotational inertia
body:getWorldPoint(lx, ly)Local → world
body:getWorldVector(lx, ly)Local → world vector
body:getLocalPoint(wx, wy)World → local
body:getLocalVector(wx, wy)World → local vector
body:getLinearVelocityFromWorldPoint(wx, wy)World point linear velocity
body:getLinearVelocityFromLocalPoint(lx, ly)Local point linear velocity
body:setType(type)Set type
body:getType()Return type
body:setBullet(bool)Set CCD
body:isBullet()Return CCD
body:setActive(bool)Activate/deactivate
body:isActive()Active state
body:setAwake(bool)Wake/sleep
body:isAwake()Awake state
body:setSleepingAllowed(bool)Allow sleeping
body:isSleepingAllowed()Return sleeping permission
body:setFixedRotation(bool)Fixed rotation
body:isFixedRotation()Return fixed rotation
body:setGravityScale(scale)Gravity scale
body:getGravityScale()Return gravity scale
body:setLinearDamping(d)Linear damping
body:getLinearDamping()Return linear damping
body:setAngularDamping(d)Angular damping
body:getAngularDamping()Return angular damping
body:setUserData(value)Set user data
body:getUserData()Return user data
body:getNext()Next body
body:getNextUD()Next body's user data
body:hasTouching()Whether contacts exist
body:scanTouching(cb)Traverse contacts
body:hasJoint()Whether joints exist
body:getContactList()contactedge list head
body:getJointList()jointedge list head

Fixture Methods​

MethodDescription
fixture:getType()Shape type
fixture:getBody()Owning body
fixture:getBodyUD()Owning body's user data
fixture:setDensity(d)Density
fixture:getDensity()Return density
fixture:setFriction(f)Friction coefficient
fixture:getFriction()Return friction coefficient
fixture:setRestitution(r)Restitution coefficient
fixture:getRestitution()Return restitution coefficient
fixture:setSensor(bool)Sensor
fixture:isSensor()Return sensor
fixture:testPoint(x, y)Point test
fixture:setFilterData(cat?, mask?, group?)Collision filtering
fixture:setFilterCategory(bits)Set category
fixture:setFilterMask(bits)Set mask
fixture:setFilterGroup(idx)Set group
fixture:getFilterData()Return cat, mask, group
fixture:getFilterGroup()Return group
fixture:getMass()Mass
fixture:getMassData()Return mass, cx, cy, inertia
fixture:getAABB(child?)Return lx, ly, hx, hy
fixture:setUserData(value)Set user data
fixture:getUserData()Return user data
fixture:getNext()Next fixture

Contact Methods​

MethodDescription
contact:isTouching()Whether touching
contact:setEnabled(bool)Enable/disable
contact:isEnabled()Enabled state
contact:getFixtureA()fixtureA
contact:getFixtureB()fixtureB
contact:getFixtureAB()fixtureA, fixtureB
contact:getFixtureABodyUD()bodyA_ud, fixtureA_ud
contact:getFixtureBBodyUD()bodyB_ud, fixtureB_ud
contact:getFixtureABBodyUD()4 user data values
contact:getChildIndexA()Child index A
contact:getChildIndexB()Child index B
contact:getNext()Next contact
contact:setFriction(f)Override friction
contact:getFriction()Return friction
contact:resetFriction()Reset friction
contact:setRestitution(r)Override restitution
contact:getRestitution()Return restitution
contact:resetRestitution()Reset restitution

JointEdge Methods​

MethodDescription
jointedge:getJoint()Joint object
jointedge:getJointUD()Joint user data
jointedge:getBodyB()Other body
jointedge:getBodyBUD()Other body's user data
jointedge:getNext()Next jointedge

ContactEdge Methods​

MethodDescription
contactedge:getContact()contact object
contactedge:getBodyB()Other body
contactedge:getBodyBUD()Other body's user data
contactedge:getNext()Next contactedge

9. Complete Examples​

Basic Physics: Falling and Collisions under Gravity​

Demonstrates creation of World, Body, and Fixture and the physics simulation loop.

usemod('b2d')

gravityX = 0
gravityY = 10 -- Positive = downward
meter = 16 -- 1 meter = 16 pixels

-- ── Create the physics world ──────────────────────
local world = b2d.newWorld(gravityX, gravityY, true, meter)

-- ── Ground (static body) ──────────────────────────
local ground = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 10 * meter}
})
ground:createFixture({
shape = {type = 2, hx = 5 * meter, hy = 0.1 * meter}
})

-- ── Ceiling (static body) ─────────────────────────
local ceiling = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 1 * meter}
})
ceiling:createFixture({
shape = {type = 2, hx = 5 * meter, hy = 0.1 * meter}
})

-- ── Dynamic box ──────────────────────────────────
local box = world:createBody({
type = b2d.dynamicBody,
position = {x = 4 * meter, y = 5 * meter}
})
box:createFixture({
density = 1,
friction = 0.3,
restitution = 1, -- Perfectly elastic
shape = {type = 2, hx = 0.1 * meter, hy = 0.1 * meter}
})

-- ── Collision collection table ───────────────────
local contacttbl = {}

function step()
local contacts = world:stepWithContact(1/30, 6, 2, contacttbl)
local bx, by = box:getPosition()
-- bx and by are pixel coordinates, ready for drawing
end

function _update()
step()
-- Apply an upward force with button 4
if btn(4) then
box:applyForce(0, -1, true)
end
end

function _draw()
cls()
world:drawDebugData(0x13)
drawTxt_h(string.format("cpu:%.1f%%,fps:%2d", stat(1)*100, stat(7)), 50, 20, white, 0, 16)
end

Zero-Gravity Bouncing Balls​

Demonstrates elastic collisions in zero gravity.

usemod('b2d')

local meter = 32
local world = b2d.newWorld(0, 0, true, meter) -- Zero gravity

-- Top and bottom barriers
local wall1 = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 10 * meter}
})
wall1:createFixture({
shape = {type = 2, hx = 5 * meter, hy = 0.1 * meter}
})

local wall2 = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 1 * meter}
})
wall2:createFixture({
shape = {type = 2, hx = 5 * meter, hy = 0.1 * meter}
})

-- Bouncing ball
local ball = world:createBody({
type = b2d.dynamicBody,
position = {x = 4 * meter, y = 5 * meter}
})
ball:createFixture({
density = 1,
friction = 0.3,
restitution = 1,
shape = {type = 2, hx = 0.1 * meter, hy = 0.1 * meter}
})

local contacttbl = {}

function _update()
world:stepWithContact(1/30, 6, 2, contacttbl)
if btn(4) then
ball:applyForce(0, -1, true)
end
end

function _draw()
cls()
world:drawDebugData(0x13)
end

User Data and Collision Traversal​

Demonstrates setUserData / scanTouching.

usemod('b2d')

local meter = 16
local world = b2d.newWorld(0, 10, true, meter)

local ground = world:createBody({
type = b2d.staticBody,
position = {x = 7 * meter, y = 12 * meter}
})
ground:setUserData("ground")
ground:createFixture({shape = {type = 2, hx = 5 * meter, hy = 0.5 * meter}})

local ball = world:createBody({
type = b2d.dynamicBody,
position = {x = 4 * meter, y = 2 * meter}
})
ball:setUserData("ball")
ball:createFixture({
density = 1,
restitution = 0.5,
shape = {type = 0, radius = 0.5 * meter, p = {0, 0}}
})

local contacttbl = {}

function _update()
local contacts = world:stepWithContact(1/30, 8, 3, contacttbl)

-- Iterate over the collision table
for i, c in ipairs(contacts) do
-- c = {bool, bodyA, bodyB, fixtureA, fixtureB}
end

-- Or iterate through the body
if ball:hasTouching() then
ball:scanTouching(function(ba_ud, bb_ud, fa_ud, fb_ud)
if ba_ud == "ground" or bb_ud == "ground" then
-- The ball hits the ground
end
return false -- Continue iteration
end)
end
end

function _draw()
cls()
world:drawDebugData()
end