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'):
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
- Global functions and constants
- World
- Body
- Fixture
- Joint
- Contact
- JointEdge and ContactEdge
- Complete API index
- Complete examples
1. Global Functions and Constants
Constants
| Constant | Value | Description |
|---|
b2d.staticBody | 0 | Static body—does not move or respond to forces |
b2d.kinematicBody | 1 | Kinematic body—moves through assigned velocity, unaffected by forces |
b2d.dynamicBody | 2 | Dynamic body—fully participates in physics simulation |
Factory Functions
| Function | Description |
|---|
b2d.newWorld(gx?, gy?, sleep?, meter?) | Create a physics world → world |
Parameters:
gx — Gravity X component, default 0gy — Gravity Y component, default 0 (positive points downward)sleep — Allow sleeping optimization, default truemeter — 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:
| Field | Type | Description |
|---|
type | int | Body type: 0=static, 1=kinematic, 2=dynamic |
position | {x,y} | Initial position (pixels) |
angle | number | Initial angle (radians) |
linearVelocity | {x,y} | Initial linear velocity |
angularVelocity | number | Initial angular velocity |
linearDamping | number | Linear damping |
angularDamping | number | Angular damping |
allowSleep | bool | Allow sleeping |
awake | bool | Initially awake |
fixedRotation | bool | Fix rotation |
bullet | bool | Enable CCD continuous collision detection |
active | bool | Active state |
gravityScale | number | Gravity 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 8positionIterations — Position solver iteration count, default 3
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
| Method | Description |
|---|
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:
| Field | Type | Description |
|---|
density | number | Density |
friction | number | Friction coefficient |
restitution | number | Restitution coefficient |
isSensor | bool | Sensor (detects collisions without a physical response) |
filter | table | Collision filter: {categoryBits, maskBits, groupIndex} |
shape | table | Shape definition (below) |
Shape Definitions
The shape subtable must contain type, matching the Box2D shape type enum:
| type | Shape | Additional fields |
|---|
| 0 | circle | p={x,y} (center), radius |
| 1 | edge | vertex1={x,y}, vertex2={x,y}, optional vertex0, vertex3 (ghost vertices) |
| 2 | polygon | Method 1: hx, hy, optional center, angle for a rectangle; method 2: vertices (array of 3~8 {x,y} vertices) |
| 3 | chain | vertex (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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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) |
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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.
| Field | Description |
|---|
anchor | Anchor {x,y} (localAnchor computed automatically) |
localAnchorA | Local anchor on bodyA |
localAnchorB | Local anchor on bodyB |
referenceAngle | Reference angle |
enableLimit | Enable angular limits |
lowerAngle | Lower angle limit |
upperAngle | Upper angle limit |
enableMotor | Enable motor |
motorSpeed | Motor speed |
maxMotorTorque | Maximum motor torque |
Prismatic Joint
A joint translating along an axis.
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
localAxisA | Local axis direction |
referenceAngle | Reference angle |
enableLimit | Enable translation limits |
lowerTranslation | Lower limit |
upperTranslation | Upper limit |
enableMotor | Enable motor |
motorSpeed | Motor speed |
maxMotorForce | Maximum motor force |
Distance Joint
Maintains a fixed distance between two anchors.
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
length | Length (computed automatically if ≤0) |
frequencyHz | Spring frequency |
dampingRatio | Damping ratio |
Pulley Joint
Simulates a pulley connecting two Bodies by ropes.
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
groundAnchorA, groundAnchorB | Ground anchors |
lengthA, lengthB | Rope lengths |
ratio | Pulley ratio |
Mouse Joint
Drags a body with the mouse.
| Field | Description |
|---|
target | Target point {x,y} |
maxForce | Maximum force |
frequencyHz | Spring frequency |
dampingRatio | Damping ratio |
Gear Joint
| Field | Description |
|---|
ratio | Gear ratio |
Wheel Joint
A wheel with a spring.
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
localAxisA | Local axis direction |
enableMotor | Enable motor |
maxMotorTorque | Maximum motor torque |
motorSpeed | Motor speed |
frequencyHz | Spring frequency |
dampingRatio | Damping ratio |
Weld Joint
Welds two bodies together.
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
referenceAngle | Reference angle |
frequencyHz | Spring frequency |
dampingRatio | Damping ratio |
Friction Joint
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
maxForce | Maximum force |
maxTorque | Maximum torque |
Rope Joint
| Field | Description |
|---|
localAnchorA, localAnchorB | Local anchors |
maxLength | Maximum length |
Common Joint Methods
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
joint:setMaxForce(force) | Set maximum force |
joint:getMaxForce() | Return maximum force |
| Method | Description |
|---|
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 |
JointEdge
Body joint list nodes, used to traverse all joints on a Body.
| Method | Description |
|---|
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 |
Body contact list nodes, used to traverse all contacts on a Body.
| Method | Description |
|---|
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/constant | Description |
|---|
b2d.newWorld(gx?, gy?, sleep?, meter?) | Create a physics world → world |
b2d.staticBody | 0 Static body |
b2d.kinematicBody | 1 Kinematic body |
b2d.dynamicBody | 2 Dynamic body |
World Methods
| Method | Description |
|---|
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
| Method | Description |
|---|
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
| Method | Description |
|---|
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 |
| Method | Description |
|---|
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
| Method | Description |
|---|
jointedge:getJoint() | Joint object |
jointedge:getJointUD() | Joint user data |
jointedge:getBodyB() | Other body |
jointedge:getBodyBUD() | Other body's user data |
jointedge:getNext() | Next jointedge |
| Method | Description |
|---|
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