3D Physics allows you to simulate the motion and collision of hard-surface objects. Instead of animating every movement yourself, you can let gravity, forces and collisions make objects fall, bounce, slide and tumble. Joints let you connect objects to build things such as swinging doors and moving machinery.
An object has a body that controls its motion and one or more colliders that describe its collision shape. The shape you use for physics can be simpler than the mesh you draw: a box can represent a crate, a sphere can represent a ball, and several shapes can combine to represent a more complex object.
Bodies live in a world, which simulates their motion together. This guide uses a standalone world that you advance yourself. When you attach physics bodies to scene entities, the scene advances its world and keeps the entities in sync automatically.
local world = physics3d.world {
gravity = vec3(0, -9.8, 0),
substeps = 4,
}
local ground = world:body(STATIC, vec3(0, -1, 0))
ground:box(vec3(10, 1, 10))
local ball = world:body(DYNAMIC, vec3(0, 5, 0))
local sphere = ball:sphere(0.5)
sphere.density = 2
-- Call once per fixed simulation tick:
world:step(1 / 60)Use the global constants STATIC, DYNAMIC and KINEMATIC. Static bodies are immovable scenery. Dynamic bodies respond to gravity, forces and collisions. Kinematic bodies follow assigned velocities and can push dynamic bodies. world:step() without an argument uses the runtime fixed delta. substeps controls solver subdivisions (1–64), not the number of application updates.
Colliders describe where objects collide; they do not draw anything. For a standalone body, use its position and rotation to place the mesh you draw. After each simulation step, these values describe the object’s new pose. For a body attached to a scene entity, give the entity a mesh and let the scene update its transform. Do not also step the scene’s physics world yourself.
Shapes attach directly to a body. Their centres and capsule endpoints are in body-local space. Positional and named-options constructors are equivalent:
body:sphere(0.5, vec3(0, 1, 0))
body:sphere { radius = 0.5, center = vec3(0, 1, 0) }
body:box(vec3(1, 2, 1), vec3(0, 2, 0))
body:box { halfExtents = vec3(1, 2, 1), center = vec3(0, 2, 0) }
-- Horizontal capsule: endpoints are the hemisphere centres.
body:capsule(0.5, vec3(-1, 0, 0), vec3(1, 0, 0))
body:capsule {
radius = 0.5,
pointA = vec3(-1, 0, 0),
pointB = vec3(1, 0, 0),
}
-- Upright capsule along local Y:
body:capsule(0.5, 2, vec3(0, 1, 0))
body:capsule { radius = 0.5, height = 2, center = vec3(0, 1, 0) }The optional centre defaults to zero. Boxes use half-extents, so vec3(1,2,1) gives full dimensions 2 by 4 by 2. Capsule height is the straight segment between hemisphere centres; total length is height + 2 * radius. Both endpoints must be provided together. Do not combine endpoints with height/center options. Coincident endpoints produce a sphere-like capsule. Radii and box half-extents must be positive; capsule height may be zero. Existing flattened numeric forms such as body:box(1, 2, 1, 0, 2, 0) remain available.
Options default to radius 1, box half-extents vec3(1), upright capsule height 2, and centre vec3(0). Shape properties are mutable:
local capsule = body:capsule(0.5, vec3(-1, 0, 0), vec3(1, 0, 0))
capsule.center = vec3(0, 2, 0) -- translates both endpoints
capsule.height = 4 -- resizes along the existing horizontal axis
capsule.pointB = vec3(3, 2, 0) -- keeps pointA fixedCapsules expose radius, pointA, pointB, center and height. A zero-length capsule retains its last axis for later height edits (Y initially). Boxes expose halfExtents and center; size remains an alias for halfExtents. Spheres expose radius and center. Edits update collision geometry and body mass immediately. Nonuniform scaling cannot produce an exact circular capsule: the native radius uses the largest stretch perpendicular to its axis.
movingBody:hull(myMesh)
staticBody:staticMesh(levelMesh)hull builds a convex hull from vertices. Concavities are filled in; triangle topology does not define the hull. It works on moving bodies. Hulls support up to 128 vertices and may simplify the input. staticMesh preserves triangle geometry and requires a static body. To represent a moving concave object, attach multiple convex colliders to one body. body:mesh(mesh, convex) still works but prints a deprecation warning; use the explicit constructors instead.
There are no standalone physics3d plane, cone or cylinder constructors in this Lua API. Use a box for a floor or an appropriate mesh hull for other convex shapes.
Collider density and volume determine body mass, local centre of mass and local inertia. Multiple colliders contribute to the same body. body.mass, body.localCenterOfMass and body.inertia are read-only calculated values. Density defaults to 1; zero excludes a shape from automatic mass calculation. Sensors also contribute mass unless their density is zero.
Advanced overrides are explicit:
body:setMassData(5, vec3(0, 0, 0), mat3(2))
body:resetMassData() -- return to collider-derived propertiesThe inertia argument is a symmetric positive-definite mat3 about the specified local centre of mass. Adding, removing or editing geometry, changing density, or changing body type resets the override. Changes to another body do not. With world units in metres, density is kg/m³ and inertia is kg·m².
Use friction to control sliding, restitution to control bouncing, and rollingResistance to slow rolling spheres and capsules. When two colliders meet, their friction values are combined using the geometric mean and the larger restitution value determines the bounce.
A standalone world takes its gravity from world.gravity. A scene sets its world’s gravity from scene.physics3d.gravity before every step, so change that setting rather than scene.world3d.gravity:
local s = scene.default3d()
s.physics3d.gravity = vec3(0, -20, 0)Use gravityScale to change how strongly gravity affects a single body. It multiplies the world’s gravity and defaults to 1:
balloon.gravityScale = -0.2 -- drifts upward
feather.gravityScale = 0.1 -- falls slowly
drone.gravityScale = 0 -- ignores gravityApply a force to push an object over time, or an impulse for a sudden kick. Torque makes it turn. You can also set velocity directly when you want to control how fast an object moves or spins.
Distances use your scene’s world units, and mass is measured in kilograms. If one world unit represents one metre, forces are in newtons and torques in newton-metres. Angles and angular speeds use degrees and degrees per second.
body:applyForce(vec3(0, 100, 0)) -- reapply each step for sustained force
body:applyImpulse(vec3(0, 10, 0)) -- instantaneous change of momentum
body:applyTorque(vec3(0, 5, 0))
body.linearVelocity = vec3(1, 0, 0)
body.angularVelocity = vec3(0, 90, 0) -- degrees/secondPosition and rotation assignments teleport. For a moving kinematic platform, set a target to generate velocities for subsequent simulation:
local target = physics3d.frame()
target.origin = vec3(10, 2, 0)
platform:setTargetTransform(target, 0.5)Use a positive time step and a kinematic body. The target is approximately reached if stepped for that duration without changing the resulting velocity. Sleep thresholds may suppress very small movements. Use body.sleepThreshold to control when slow-moving bodies can rest. Motion locks use physics3d.freezePositionX and related flags, combined with bitwise OR; physics3d.none clears them.
Use collision callbacks to play impact sounds, apply damage or detect when objects touch or separate. Callbacks run after each simulation step. Assign callbacks to a body to receive its collision events:
ball.onCollisionBegan = function(contact)
print(contact.otherBody, contact.worldPoint)
savedContact = contact -- safe to keep after the callback
end
ball.onCollisionHit = function(contact)
print("Impact speed", contact.approachSpeed)
end
ball.onCollisionEnded = function(contact)
print("Separated", contact.otherBody)
endAssigning a callback turns on the events it needs for all of the body’s colliders, including colliders added later. Assigning nil turns them off again. Contacts that are already touching when you assign the callback are reported once they separate and touch again.
A contact snapshot provides body, otherBody, collider, otherCollider, touching, sensor, points, pointCount, worldPoint, worldNormal and approachSpeed. Normals point from the callback’s body toward the other body. Begin events contain copied manifold points; hit events contain an impact point and positive approach speed. End/sensor events have no geometry: points is empty, worldPoint nil and normal zero. Snapshots do not change on later steps; referenced bodies/colliders can subsequently become destroyed. No impulse field is exposed.
For a non-solid trigger:
local trigger = world:body(STATIC)
local area = trigger:box(vec3(2, 2, 2))
area.sensor = true
area.sensorEventsEnabled = true
sphere.sensorEventsEnabled = true -- opt in the visiting shape too
trigger.onSensorBegan = function(contact)
print("Entered", contact.otherBody)
end
trigger.onSensorEnded = function(contact)
print("Exited", contact.otherBody)
endSensor visitors must be convex shapes. Sensor event flags default to false. Callbacks may create/edit objects and request deferred destruction. Re-entering step on the same world is rejected. End events whose native shapes were already destroyed are skipped. Collision callbacks run after the simulation has finished resolving contacts.
Colliders have category, mask and group properties. Category/mask expose 32 bits; category defaults to 1 and mask to 0xFFFFFFFF. Both masks must accept the other collider’s category. Equal nonzero groups override masks: positive collides, negative does not.
sphere.category = 2
local origin, direction = vec3(0, 10, 0), vec3(0, -1, 0)
local hit = world:raycast(origin, direction, { distance = 100, mask = 2 })
local hits = world:raycastAll(origin, direction, { distance = 100 })
local sweep = world:sphereCast(origin, direction, {
distance = 100, radius = 0.25, mask = 2,
})Closest casts return a hit or nil; raycastAll returns a nearest-first array. Directions are normalized. Existing positional query forms also work. Options default to distance 10000, mask 0xFFFFFFFF and sphere-cast radius 1. Triangle casts are subject to native sidedness and initial-overlap behavior.
Hits contain point, normal, fraction, collider and body. Static-mesh hits also contain the original one-based triangleIndex, barycentric (vec3) and interpolated uv. Metadata unavailable for other shapes is zero; missing mesh UVs give zero UV.
-- Anchor and axis are LOCAL to door, not world coordinates.
local hinge = door:hinge(wall, vec3(-0.5, 0, 0), vec3(0, 1, 0))
hinge.lowerLimit = -90
hinge.upperLimit = 90
hinge.useLimit = true
hinge.useMotor = true
hinge.motorSpeed = 45
hinge.maxTorque = 20A hinge permits rotation about one axis. Omitting the other body attaches it to the world. The two-anchor overload takes one local anchor/axis pair per body. Angles, limits and motor speeds use degrees. maxTorque controls how much turning force the motor can apply. useLimit explicitly enables limits; assigning bounds alone does not enable them. Joint reactionForce/reactionTorque are read-only vectors with no inverse-time-step argument. collideConnected controls whether the joined bodies can collide with each other.
A hinge spring can be configured at construction:
local hinge = door:hinge(wall, vec3(-0.5, 0, 0), vec3(0, 1, 0), {
spring = { targetAngle = 0, hertz = 3, dampingRatio = 0.8 },
limits = { lower = -90, upper = 90 },
})
hinge.useSpring = false -- retains spring settings for later
hinge.useSpring = true
hinge.targetAngle = 45
hinge.springHertz = 2
hinge.springDampingRatio = 1
hinge:setLimits(-60, 60) -- sets both bounds and enables useLimitSupplying spring or limits enables that feature initially. Top-level useSpring and useLimit options can explicitly override this. All three hinge constructor forms accept the final options table when anchors/axes are vec3 values. Spring defaults are targetAngle 0 degrees, hertz 3 and dampingRatio 1. Limit tables require both lower and upper. setLimits validates the pair and clamps it to the supported [-178.2,178.2] degree range. Individual bound assignments preserve useLimit.
The spring pulls toward targetAngle. Higher frequency gives a stiffer response. Damping below 1 permits oscillation, 1 targets critical damping, and larger values are overdamped. Frequency zero disables spring response. Spring parameters must be finite and nonnegative, except targetAngle which accepts [-180,180] degrees. Changing spring settings wakes connected bodies. Settings are preserved when you disable and re-enable the joint.
For a motor that aims toward a particular angle, enable useMotorTarget. With useMotor enabled, it computes a motor speed from the error to motorTarget divided by the time step, with the motor limited by maxTorque. A spring is not capped by maxTorque. Use a spring for an elastic hinge and a target motor for a torque-limited actuator. Spring, motor and limits are independent and may operate simultaneously; their forces can oppose each other when given conflicting targets. Use useMotor, useLimit and useSpring to turn each feature on or off.
body:slider(other, frame) supports translation limits; the world-only overload is unimplemented. The legacy generic constructor behaves as a spherical joint, not a configurable six-axis constraint. See Physics 3D for the exact supported joint surface.
- Use density-derived mass, or setMassData/resetMassData; direct mass assignment is no longer supported. Inertia is now the local tensor about the centre of mass. - Use hull/staticMesh instead of the deprecated mesh boolean selector. - Replace rollingFriction with rollingResistance; remove margin. - Replace linearSleepingThreshold/angularSleepingThreshold with sleepThreshold. - Replace collidConnected with collideConnected and reaction-force/torque calls with property access. - Use buffered body callbacks and explicitly enable the relevant collider events. - Retune materials and motor torque as needed. Simulation trajectories need not match Bullet even when geometry and initial conditions match.
3D Physics allows you to simulate the motion and collision of hard-surface objects in your scenes and games. Use it to make balls bounce, crates tumble, doors swing and moving platforms carry objects.
Each object is represented by a body, which describes how it moves, and one or more colliders, which define its shape for collisions. Bodies are rigid: they can move and rotate, but do not bend or deform. A collider can be a simple shape, such as a box or sphere, or a shape built from a mesh. It does not have to match every detail of the object you draw.
A world simulates these bodies together, updating their positions and rotations as gravity, forces and collisions act on them. Use those transforms to draw your objects, or attach bodies to scene entities to let the scene keep their motion in sync. Choose static bodies for scenery, dynamic bodies for objects that react to their surroundings, and kinematic bodies for movement you control.
You can also connect bodies with joints, respond to collisions to trigger gameplay, and cast rays to find objects along a path. See 3D Physics to get started.
world
A standalone simulation world. Scene-owned physics worlds are stepped by the scene.
world(options)
Create a world. options may contain gravity (vec3, default vec3(0,-9.8,0)) and substeps (integer, default 4). Both can also be changed afterward.
| options | table, optional. Named options described above; omitted fields use their documented defaults. |
physics3d.world |
world:body(type, position)
Create a body at a vec3 position, default zero. The flattened form body(type, x, y, z) is also supported. STATIC bodies are immovable; DYNAMIC bodies respond to forces; KINEMATIC bodies follow assigned velocities and can push dynamic bodies.
| type | integer. Global body type constant STATIC, KINEMATIC or DYNAMIC. |
| position | vec3, optional. Initial body origin in world space; defaults to zero. |
physics3d.body |
world:step(deltaTime)
Advance by a nonnegative, finite number of seconds. Omission uses the runtime fixed delta. Prefer a fixed time step, such as 1/60. Dispatches buffered events after simulation and processes deferred destruction. Calling this recursively from a callback on the same world raises an error.
| deltaTime | number, optional. Simulation duration in seconds. |
world.gravity
Gravity acceleration. Must be finite. A scene sets its world’s gravity from scene.physics3d.gravity before every step; change that setting for scene bodies.
world.substeps
Solver substeps per call to step, from 1 through 64; default 4.
world:raycast(origin, direction, distance, mask)
Find the closest collider hit, returning a physics3d.rayHit or nil. origin and direction are vec3 values; direction is normalized. Options: distance (default 10000) and mask (default 0xFFFFFFFF). Zero direction or distance gives no hit. A negative distance uses the legacy 10000-unit range. Triangle mesh casts respect native triangle sidedness; casts starting inside shapes may not report those shapes.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| distance | number. Maximum travel distance in world units. |
| mask | integer, optional. Accepted collider category bits, default 0xFFFFFFFF. |
physics3d.rayHit |
world:raycast(origin, direction, options)
Find the closest collider hit, returning a physics3d.rayHit or nil. origin and direction are vec3 values; direction is normalized. Options: distance (default 10000) and mask (default 0xFFFFFFFF). Zero direction or distance gives no hit. A negative distance uses the legacy 10000-unit range. Triangle mesh casts respect native triangle sidedness; casts starting inside shapes may not report those shapes.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| options | table. Named options described above; omitted fields use their documented defaults. |
physics3d.rayHit |
world:raycastAll(origin, direction, distance, mask)
Return an array of hits sorted by increasing fraction; empty when nothing is hit. Options and defaults match raycast. A mesh can contribute multiple hits.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| distance | number, optional. Maximum travel distance in world units. |
| mask | integer, optional. Accepted collider category bits, default 0xFFFFFFFF. |
table |
world:raycastAll(origin, direction, options)
Return an array of hits sorted by increasing fraction; empty when nothing is hit. Options and defaults match raycast. A mesh can contribute multiple hits.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| options | table. Named options described above; omitted fields use their documented defaults. |
table |
world:sphereCast(origin, direction, distance, radius, mask)
Sweep a sphere and return the closest physics3d.rayHit or nil. Options: distance (10000), radius (1) and mask (0xFFFFFFFF). Radius must be positive and finite; invalid radius produces no hit. Query masks select collider category bits and expose the lower 32 native bits.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| distance | number. Maximum travel distance in world units. |
| radius | number. Positive finite radius in world units. |
| mask | integer, optional. Accepted collider category bits, default 0xFFFFFFFF. |
physics3d.rayHit |
world:sphereCast(origin, direction, options)
Sweep a sphere and return the closest physics3d.rayHit or nil. Options: distance (10000), radius (1) and mask (0xFFFFFFFF). Radius must be positive and finite; invalid radius produces no hit. Query masks select collider category bits and expose the lower 32 native bits.
| origin | vec3. World-space starting point of the cast. |
| direction | vec3. Cast direction, normalized internally. |
| options | table. Named options described above; omitted fields use their documented defaults. |
physics3d.rayHit |
body:destroy()
Request destruction at the next cleanup point, normally the next step (or after the current event batch). Attached colliders and joints are invalidated. Retained wrappers report destroyed; accessing native properties afterward raises an error.
body:sphere(radius, center)
Attach a sphere. Center is a body-local vec3, default zero. Options: radius (default 1), center (zero). Radius must be positive and finite. Flattened sphere(radius, x, y, z) remains supported.
| radius | number. Positive finite radius in world units. |
| center | vec3, optional. Body-local centre, default zero. |
physics3d.sphere |
body:sphere(options)
Attach a sphere. Center is a body-local vec3, default zero. Options: radius (default 1), center (zero). Radius must be positive and finite. Flattened sphere(radius, x, y, z) remains supported.
| options | table. Named options described above; omitted fields use their documented defaults. |
physics3d.sphere |
body:box(halfExtents, center)
Attach a box. Half-extents and center are body-local vec3 values. Options: halfExtents (default vec3(1)), center (zero). Half-extents must be positive and finite: vec3(1,2,1) gives full dimensions 2 by 4 by 2. Flattened box(hx, hy, hz[, x, y, z]) remains supported.
| halfExtents | vec3. Positive half-width, half-height and half-depth. |
| center | vec3, optional. Body-local centre, default zero. |
physics3d.box |
body:box(options)
Attach a box. Half-extents and center are body-local vec3 values. Options: halfExtents (default vec3(1)), center (zero). Half-extents must be positive and finite: vec3(1,2,1) gives full dimensions 2 by 4 by 2. Flattened box(hx, hy, hz[, x, y, z]) remains supported.
| options | table. Named options described above; omitted fields use their documented defaults. |
physics3d.box |
body:capsule(radius, pointA, pointB)
Attach a capsule using body-local hemisphere centres pointA and pointB, or an upright capsule along local Y using height and optional center. Height is the straight segment length, so total length is height + 2 * radius.
Options accept radius (default 1), and either both pointA/pointB or height (default 2)/center (zero). Mixing endpoint and height/center options raises an error. Endpoints must be finite; radius positive and finite; height nonnegative and finite. Coincident endpoints produce a sphere-like capsule. Flattened capsule(radius, height, x, y, z) remains supported.
| radius | number. Positive finite radius in world units. |
| pointA | vec3. First body-local hemisphere centre. |
| pointB | vec3. Second body-local hemisphere centre. |
physics3d.capsule |
body:capsule(radius, height, center)
Attach a capsule using body-local hemisphere centres pointA and pointB, or an upright capsule along local Y using height and optional center. Height is the straight segment length, so total length is height + 2 * radius.
Options accept radius (default 1), and either both pointA/pointB or height (default 2)/center (zero). Mixing endpoint and height/center options raises an error. Endpoints must be finite; radius positive and finite; height nonnegative and finite. Coincident endpoints produce a sphere-like capsule. Flattened capsule(radius, height, x, y, z) remains supported.
| radius | number. Positive finite radius in world units. |
| height | number. Nonnegative length between capsule hemisphere centres. |
| center | vec3, optional. Body-local centre, default zero. |
physics3d.capsule |
body:capsule(options)
Attach a capsule using body-local hemisphere centres pointA and pointB, or an upright capsule along local Y using height and optional center. Height is the straight segment length, so total length is height + 2 * radius.
Options accept radius (default 1), and either both pointA/pointB or height (default 2)/center (zero). Mixing endpoint and height/center options raises an error. Endpoints must be finite; radius positive and finite; height nonnegative and finite. Coincident endpoints produce a sphere-like capsule. Flattened capsule(radius, height, x, y, z) remains supported.
| options | table. Named options described above; omitted fields use their documented defaults. |
physics3d.capsule |
body:hull(mesh)
Attach a convex hull built from the mesh vertices. Triangle topology and concavities do not define the collision surface. Supports dynamic, kinematic and static bodies. Box3D limits hulls to 128 vertices and may simplify input.
| mesh | mesh. Source vertex/index geometry. |
physics3d.mesh |
body:staticMesh(mesh)
Attach indexed triangle geometry to a static body. Moving triangle meshes are not supported by this adapter; use hulls or multiple convex colliders for moving concave objects. Changing the body to a non-static type raises an error.
| mesh | mesh. Source vertex/index geometry. |
physics3d.mesh |
body:mesh(mesh, convex)
Deprecated: prints a warning on every call. convex=true selects hull geometry; false (the default) selects static triangle geometry. Use hull() or staticMesh() instead.
| mesh | mesh. Source vertex/index geometry. |
| convex | boolean, optional. True builds a convex hull; false selects static triangle geometry. |
physics3d.mesh |
body:setMassData(mass, localCenter, localInertia)
Override a dynamic body’s mass, local centre of mass (vec3) and inertia tensor about that centre (mat3). Mass must be positive and finite; the tensor must be finite, symmetric and positive definite. Geometry, density and body-type changes restore calculated mass data. Changes to other bodies do not reset this override.
| mass | number. Positive finite body mass in kilograms. |
| localCenter | vec3. Centre of mass in body-local coordinates. |
| localInertia | mat3. Local symmetric positive-definite inertia tensor about the centre of mass. |
body:resetMassData()
Recalculate mass, centre of mass and inertia from the attached geometry and densities.
body:setTargetTransform(target, deltaTime, wake)
Set velocities to reach a world-space physics3d.frame after deltaTime seconds. Requires a kinematic body and a positive finite time step. Wake defaults to true. This drives subsequent simulation; it does not teleport. Motion smaller than the sleep threshold may be ignored.
| target | physics3d.frame. Target world-space position and orientation. |
| deltaTime | number. Simulation duration in seconds. |
| wake | boolean, optional. Whether significant target motion may wake the body; default true. |
body:applyForce(force, worldPoint)
Apply a force for the simulation step, optionally at a world-space point (otherwise the centre of mass). Apply again each step for a sustained force.
| force | vec3. World-space force vector. |
| worldPoint | vec3, optional. World-space point on the body. |
body:applyTorque(torque)
Apply a torque vector for the simulation step.
| torque | vec3. World-space torque vector. |
body:applyImpulse(impulse, worldPoint)
Apply an instantaneous linear impulse, optionally at a world-space point.
| impulse | vec3. World-space linear or angular impulse vector. |
| worldPoint | vec3, optional. World-space point on the body. |
body:applyAngularImpulse(impulse)
Apply an instantaneous angular impulse.
| impulse | vec3. World-space linear or angular impulse vector. |
body:worldPoint(localPoint)
Transform a body-local point to world space.
| localPoint | vec3. Point in body-local coordinates. |
vec3 |
body:worldVector(localVector)
Rotate a body-local vector to world space.
| localVector | vec3. Vector in body-local coordinates. |
vec3 |
body:localPoint(worldPoint)
Transform a world-space point to body-local space.
| worldPoint | vec3. World-space point on the body. |
vec3 |
body:localVector(worldVector)
Rotate a world-space vector to body-local space.
| worldVector | vec3. Vector in world coordinates. |
vec3 |
body:velocityAtLocalPoint(localPoint)
Return world-space velocity at a body-local point.
| localPoint | vec3. Point in body-local coordinates. |
vec3 |
body:velocityAtWorldPoint(worldPoint)
Return world-space velocity at a world-space point.
| worldPoint | vec3. World-space point on the body. |
vec3 |
body:hinge(anchor, axis, options)
Attach a hinge to the world or another body. In the single-anchor forms, anchor and axis are local to the receiving body; the corresponding frame on the other body/world is derived at creation. In the two-anchor form, each anchor and axis is local to its respective body. Axes must be nonzero.
A final options table may contain spring = { targetAngle=0, hertz=3, dampingRatio=1 } and limits = { lower=..., upper=... }. Each supplied table enables that feature. Optional top-level useSpring and useLimit override this, allowing stored settings to start disabled. Spring values must be finite, targetAngle within [-180,180] degrees, and hertz/dampingRatio nonnegative. Both limit bounds are required and lower must not exceed upper. Invalid options raise an error before a joint is created. Options-table calls require vec3 anchors/axes.
| anchor | vec3. Anchor local to the receiving body. |
| axis | vec3. Nonzero axis local to the receiving body. |
| options | table, optional. Optional spring/limits configuration and explicit useSpring/useLimit toggles. |
physics3d.hinge |
body:hinge(other, anchor, axis, options)
Attach a hinge to the world or another body. In the single-anchor forms, anchor and axis are local to the receiving body; the corresponding frame on the other body/world is derived at creation. In the two-anchor form, each anchor and axis is local to its respective body. Axes must be nonzero.
A final options table may contain spring = { targetAngle=0, hertz=3, dampingRatio=1 } and limits = { lower=..., upper=... }. Each supplied table enables that feature. Optional top-level useSpring and useLimit override this, allowing stored settings to start disabled. Spring values must be finite, targetAngle within [-180,180] degrees, and hertz/dampingRatio nonnegative. Both limit bounds are required and lower must not exceed upper. Invalid options raise an error before a joint is created. Options-table calls require vec3 anchors/axes.
| other | physics3d.body. Other body connected by the joint. |
| anchor | vec3. Anchor local to the receiving body. |
| axis | vec3. Nonzero axis local to the receiving body. |
| options | table, optional. Optional spring/limits configuration and explicit useSpring/useLimit toggles. |
physics3d.hinge |
body:hinge(other, anchorA, axisA, anchorB, axisB, options)
Attach a hinge to the world or another body. In the single-anchor forms, anchor and axis are local to the receiving body; the corresponding frame on the other body/world is derived at creation. In the two-anchor form, each anchor and axis is local to its respective body. Axes must be nonzero.
A final options table may contain spring = { targetAngle=0, hertz=3, dampingRatio=1 } and limits = { lower=..., upper=... }. Each supplied table enables that feature. Optional top-level useSpring and useLimit override this, allowing stored settings to start disabled. Spring values must be finite, targetAngle within [-180,180] degrees, and hertz/dampingRatio nonnegative. Both limit bounds are required and lower must not exceed upper. Invalid options raise an error before a joint is created. Options-table calls require vec3 anchors/axes.
| other | physics3d.body. Other body connected by the joint. |
| anchorA | vec3. Anchor local to the receiving body. |
| axisA | vec3. Axis local to the receiving body. |
| anchorB | vec3. Anchor local to the other body. |
| axisB | vec3. Axis local to the other body. |
| options | table, optional. Optional spring/limits configuration and explicit useSpring/useLimit toggles. |
physics3d.hinge |
body:slider(other, frame)
Attach a slider using a frame local to this body; the other frame is derived at creation. The frame’s local X axis is the sliding axis. The world-only overload is unimplemented and returns nil.
| other | physics3d.body. Other body connected by the joint. |
| frame | physics3d.frame. Joint frame local to the receiving body. |
physics3d.slider |
body:generic(other, frame)
Legacy compatibility constructor backed by a spherical joint: translation is constrained and rotation is free. Single frames are local to this body; the two-frame form uses one local frame per body. It is not a configurable six-axis constraint, and there is no complete generic-joint Lua property API. Prefer the supported hinge/slider APIs where applicable.
| other | physics3d.body. Other body connected by the joint. |
| frame | physics3d.frame. Joint frame local to the receiving body. |
body:generic(frameA, other, frameB)
Legacy compatibility constructor backed by a spherical joint: translation is constrained and rotation is free. Single frames are local to this body; the two-frame form uses one local frame per body. It is not a configurable six-axis constraint, and there is no complete generic-joint Lua property API. Prefer the supported hinge/slider APIs where applicable.
| frameA | physics3d.frame. Joint frame local to the receiving body. |
| other | physics3d.body. Other body connected by the joint. |
| frameB | physics3d.frame. Joint frame local to the other body. |
body:generic(frame)
Legacy compatibility constructor backed by a spherical joint: translation is constrained and rotation is free. Single frames are local to this body; the two-frame form uses one local frame per body. It is not a configurable six-axis constraint, and there is no complete generic-joint Lua property API. Prefer the supported hinge/slider APIs where applicable.
| frame | physics3d.frame. Joint frame local to the receiving body. |
body.type
STATIC, KINEMATIC or DYNAMIC. A body with a staticMesh collider cannot become dynamic or kinematic.
body.position
World-space position of the body origin. Assignment teleports the body.
body.rotation
World-space orientation. Assignment teleports orientation.
body.entity
Owning scene entity, or nil for a standalone body.
body.destroyed
Whether the native body has been destroyed.
body.linearVelocity
World-space linear velocity at the centre of mass, in world units/second.
body.angularVelocity
World-space angular velocity, in degrees/second.
body.mass
Mass in kilograms calculated from collider density and volume, or the explicit override. Static and kinematic bodies have zero simulation mass.
body.localCenterOfMass
Centre of mass in body-local coordinates.
body.inertia
Local rotational inertia about the centre of mass, in kg * world-unit squared.
body.linearDamping
Linear velocity damping.
body.angularDamping
Angular velocity damping.
body.gravityScale
Multiplier applied to the world’s gravity for this body; default 1. Use 0 to ignore gravity or a negative value to fall upward.
body.sleepingAllowed
Whether the body may sleep.
body.awake
Current awake state. Assign true to wake an enabled body.
body.sleepThreshold
Single native motion threshold in world units/second; must be nonnegative and finite.
body.enabled
Whether this body participates in simulation and collision queries.
body.bullet
Enable native continuous collision behavior for fast-moving bodies.
body.constraints
Combine physics3d.freezePositionX/Y/Z, freezeRotationX/Y/Z, freezePosition, freezeRotation or freezeAll using bitwise OR. Set physics3d.none to clear all locks.
body.onCollisionBegan
Contact started. Assigning this callback enables contact events for the body’s colliders. Receives one read-only physics3d.contact snapshot after stepping; snapshots can be retained. Callbacks may edit the world or request deferred destruction. Native end events referring to already destroyed shapes are skipped.
body.onCollisionEnded
Contact ended. The snapshot has touching=false and no contact geometry. Assigning this callback enables contact events for the body’s colliders. Receives one read-only physics3d.contact snapshot after stepping; snapshots can be retained. Callbacks may edit the world or request deferred destruction. Native end events referring to already destroyed shapes are skipped.
body.onCollisionHit
Impact exceeded the native hit threshold. Assigning this callback enables hit events for the body’s colliders. Includes approachSpeed and impact geometry. Receives one read-only physics3d.contact snapshot after stepping; snapshots can be retained. Callbacks may edit the world or request deferred destruction. Native end events referring to already destroyed shapes are skipped.
body.onSensorBegan
Sensor overlap started. Enable sensorEventsEnabled on sensor and visitor colliders. Receives one read-only physics3d.contact snapshot after stepping; snapshots can be retained. Callbacks may edit the world or request deferred destruction. Native end events referring to already destroyed shapes are skipped.
body.onSensorEnded
Sensor overlap ended; touching=false. Receives one read-only physics3d.contact snapshot after stepping; snapshots can be retained. Callbacks may edit the world or request deferred destruction. Native end events referring to already destroyed shapes are skipped.
collider
Base properties shared by shapes attached to a body. Shape edits recalculate mass.
collider:destroy()
Request deferred destruction. The next cleanup removes the shape and updates its body mass.
collider.destroyed
Whether the native shape has been destroyed.
collider.body
The owning body.
collider.density
Nonnegative finite mass per volume; default 1. Zero excludes a collider (including a sensor) from automatic mass.
collider.friction
Surface friction; default 0.75. Uses native geometric-mean friction mixing.
collider.restitution
Bounciness; default 0.25. Uses the native maximum of the two restitution values.
collider.rollingResistance
Resistance to rolling for spheres/capsules; default 0.125. Replaces rollingFriction.
collider.sensor
When true, reports overlap instead of a collision response. Default false. Changing this recreates native geometry; sensor density still contributes to mass.
collider.category
Collision category bitfield; default 1. Uses the lower 32 native bits (0 through 0xFFFFFFFF).
collider.mask
Accepted collision categories; default 0xFFFFFFFF. Ordinary pairs require both colliders to accept the other category.
collider.group
Signed 32-bit group index. Equal nonzero groups override masks: positive groups collide; negative groups do not. Default 0.
collider.sensorEventsEnabled
Opt in to sensor overlap events; default false. Enable on the sensor and visitors. Native sensor visitors must be convex shapes.
sphere.radius
Positive finite sphere radius.
sphere.center
Body-local centre.
box.halfExtents
Positive finite half-width, half-height and half-depth.
box.size
Alias for halfExtents; these are half dimensions, not full dimensions.
box.center
Body-local centre.
capsule
Endpoints and centre use body-local coordinates. Nonuniform scaling retains circular native caps with radius scaled by the largest stretch perpendicular to the capsule axis.
capsule.radius
Positive finite cap radius.
capsule.pointA
First hemisphere centre. Editing it keeps pointB fixed and updates centre, height and axis.
capsule.pointB
Second hemisphere centre. Editing it keeps pointA fixed and updates centre, height and axis.
capsule.center
Midpoint. Assignment translates both endpoints without changing the axis or height.
capsule.height
Nonnegative segment length. Assignment resizes symmetrically along the current axis. A zero-length capsule retains its last axis, initially Y.
mesh.mesh
Source geometry. Assignment rebuilds the shape; failed rebuilds preserve the previous geometry.
mesh.convex
Whether this wrapper uses a convex hull. The legacy mutable property remains available; switching to triangle geometry requires a static body. Prefer explicit hull/staticMesh construction.
joint
Base properties of supported hinge and slider joints. Destroying either endpoint invalidates the joint.
joint:destroy()
Request deferred destruction.
joint.destroyed
Whether the joint was destroyed.
joint.anchorA
World-space anchor on the receiving body.
joint.anchorB
World-space anchor on the other body or world.
joint.localAnchorA
Anchor local to the receiving body.
joint.localAnchorB
Anchor local to the other body; world space when attached to the world.
joint.other
Other body, or nil for a world attachment.
joint.enabled
Enable/disable the constraint while retaining settings.
joint.collideConnected
Whether connected bodies may collide. Corrected spelling of collidConnected.
joint.reactionForce
Current native constraint force; no inverse-time-step argument is required.
joint.reactionTorque
Current native constraint torque; no inverse-time-step argument is required.
hinge
A revolute joint: one axis of relative rotation. Motor, spring and limits are independent features and can be enabled together.
hinge.axis
World-space hinge axis.
hinge.angle
Relative hinge angle in degrees.
hinge.speed
Relative angular speed in degrees/second.
hinge:setLimits(lower, upper)
Set both angle bounds together and enable useLimit. Values must be finite with lower <= upper; bounds are clamped to Box3D’s [-178.2,178.2] degree range. This avoids intermediate clamping against an old bound. Wakes connected bodies. Individual lowerLimit/upperLimit assignments preserve useLimit.
| lower | number. Lower angle bound in degrees. |
| upper | number. Upper angle bound in degrees. |
hinge.useSpring
Enable the native angular spring, independently of useMotor/useMotorTarget and useLimit. Default false unless a spring table is supplied at construction. Toggling wakes connected bodies.
hinge.targetAngle
Spring equilibrium angle in degrees, within [-180,180]; default 0. Distinct from motorTarget. Changing it wakes connected bodies.
hinge.springHertz
Nonnegative finite spring frequency in cycles per second; default 3. Higher values give a stiffer response; zero disables spring response. Changing it wakes connected bodies.
hinge.springDampingRatio
Nonnegative finite damping ratio; default 1 (critical damping). Values below 1 permit oscillation; larger values are overdamped. Changing it wakes connected bodies.
hinge.useMotor
Enable the torque-limited velocity motor.
hinge.motorSpeed
Requested speed in degrees/second when useMotorTarget is false.
hinge.maxTorque
Maximum motor torque, in N*m when using metres. Unlike the old Bullet adapter this is physical torque, not a per-step impulse.
hinge.useMotorTarget
When true with useMotor enabled, calculate motor speed each step from angular error divided by the step duration. This is a target-seeking motor approximation, not a native spring.
hinge.motorTarget
Target angle in degrees when useMotorTarget is enabled.
hinge.useLimit
Explicitly enable angular limits. Assigning a bound does not enable limits.
hinge.lowerLimit
Lower angle bound in degrees. Values are clamped against the current upper bound.
hinge.upperLimit
Upper angle bound in degrees. Values are clamped against the current lower bound.
slider.useLimit
Explicitly enable translation limits.
slider.lowerLimit
Lower translation bound in world units, clamped against the upper bound.
slider.upperLimit
Upper translation bound in world units, clamped against the lower bound.
contact
An owned, read-only event snapshot. It stores no pointer into native event buffers. Body/collider references remain accessible after destruction, but their native properties do not. Geometry describes the event and does not update on later steps.
contact.body
Body receiving the callback.
contact.otherBody
Other participant.
contact.collider
Collider belonging to the receiving body.
contact.otherCollider
Other participating collider.
contact.touching
True for begin/hit events, false for end events.
contact.sensor
Whether this is a sensor overlap event.
contact.points
Array of copied world-space contact positions. Begin events copy manifold points; hits contain one impact point. End and sensor events have an empty array.
contact.pointCount
Number of copied points.
contact.worldPoint
Average copied point, or nil when geometry is unavailable.
contact.worldNormal
Points from the receiving body toward the other body. For multiple manifolds this is the first manifold normal. Zero for end/sensor events.
contact.approachSpeed
Positive approach speed for hit events, in world units/second; zero otherwise.
rayHit
Read-only query result. Mesh metadata refers to static triangle geometry, not hull topology.
rayHit.point
World-space point on the hit collider. Read-only.
rayHit.normal
World-space surface normal. Read-only.
rayHit.fraction
Fraction of the requested cast translation. Read-only.
rayHit.triangleIndex
One-based original source triangle index for a triangle mesh; zero otherwise. Read-only.
rayHit.uv
Interpolated source UV for a triangle mesh; zero when unavailable. Read-only.
rayHit.barycentric
Triangle barycentric coordinates; zero when unavailable. Read-only.
rayHit.collider
Hit collider, including the exact child on a body with multiple shapes. Read-only.
rayHit.body
Owning body. Read-only.
frame
A position/orientation pair used by joints and kinematic targets. Also available as the global frame constructor.
frame()
Create an identity frame. Assign origin and orientation explicitly before use.
physics3d.frame |
frame.origin
Frame position. Target transforms use world space; joint constructor frames use body-local space.
frame.orientation
Frame orientation quaternion; identity by default.
physics3d.none
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezePositionX
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezePositionY
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezePositionZ
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezeRotationX
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezeRotationY
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezeRotationZ
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezePosition
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezeRotation
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.
physics3d.freezeAll
Motion-lock flag for body.constraints. Combine flags with bitwise OR; none clears all locks.