Physics
Physics in Zero has two surfaces, reached in two different ways:
Physics: a Luau global you call from inside scripts and components: forces, velocity, raycasts against colliders (what is drawn with no collider, such as a Generator's scatter or a quick-geometry model, is met byrenderer.raycast, the rendering-scene-queries guide), overlaps (one at a time, or many in one call withPhysics.castMany), collision, impact and trigger events, acceleration and g-force probes, sleep control, gravity and the gravity at any point, joints, latches (hitches, couplers, docking ports that join on contact), rails (a point held to a track or a curve), wheels, collision groups, soft body reads, water and wind (Physics.water,Physics.defineWind) and what they put on a body (Physics.fluidForces), and the observation reads that report what the solver holds for a body and why it is not moving it. This is the code surface.phys: a toolbox, not a Luau global. Its verbs compose an entity + model + body + collider in one call, so you can stand up physical objects without writing a script. Drive it from any tool surface:zero physin the shell lists the verbs andzero phys <verb> --helpgives one verb's arguments,search_tools→tool_exec(return await zero.phys.<verb>(...)) does the same over MCP, andtools.use("phys", "<verb>", ...)does it from Luau. The bare name is not a global: callingphys.spawnStatic(...)in a script fails with "attempt to index nil".
Bodies are rigid or soft. A rigid body keeps its shape; a soft body (the SoftBody component, below) squashes, wobbles, drapes and dents, and with a plasticYield keeps a dent or a crumple after the impact that made it, the way a car's sheet metal stays bent after a crash, until it is repaired.
Physics simulates during play; in edit mode the world is posed, not running (the engine guide covers modes). Posed or paused, every collider stands where its entity is drawn: moving, turning or scaling an entity, or any entity above it, carries its collider with it in edit mode and with engine.paused = true, so a ray, an overlap or a height query answers where the body is drawn. A dynamic body carried that way keeps the velocity it held, and the clock resumes it from where it was carried.
It simulates at wall-clock rate, and the engine keeps stepping between your tool calls, so a body launched on one call has travelled whatever several real seconds of travel comes to by the next one. Polling a position call by call therefore reads end states rather than a trajectory. To watch the motion, sample it inside one call (read the position, task.waitFrames(n), read it again) or slow the world with engine.timeScale = 0.1 so the next call still arrives mid-flight; engine.paused = true freezes a body where it stands for a read or a capture. Otherwise verify the settled result with data: positions, rotations, raycasts and the observation reads below. The engine guide's "How fast time passes" has the whole model, including what the world does with a frame the engine lost.
Running a measurement faster than real time
On its own the simulation advances with the wall clock, so measuring an outcome over many simulated seconds (0 to 100 km/h, a braking distance, a settle time, a lap, a bridge under load) waits those seconds out. Physics.advance fast-forwards it instead: it runs a stated number of fixed steps, or the simulated seconds the nearest whole number of steps covers, as fast as the machine computes them, and returns once the last one has run, with what it ran.
-- In play, once play has started (engine.gameplayReady reads true):
engine.paused = true -- hold the start; it stays paused afterwards
local log = {}
local off = Physics.onAfterStep(function(dt, step)
table.insert(log, { step = step, speed = Physics.bodyState(car).linearVelocity.z })
end)
local ran = Physics.advance({ seconds = 12 }) -- or Physics.advance(720) for exactly 720 steps
off()
print(`{ran.steps} steps, {ran.simulatedSeconds} s simulated in {ran.wallSeconds} s of wall time`)
The steps are the steps real-time play runs, at the same dt (physics.tick_rate): the step hooks, the forces bodies hold, contact and impact events, joint breaks and fixedUpdate all run once per step, so from the same state a run driven from Physics.onBeforeStep, Physics.onAfterStep and fixedUpdate reaches the state the same steps reach at wall-clock rate: fast-forwarding changes the wall time and nothing about the result's accuracy. The step rate is what sets the accuracy, at either speed. Per-frame code (update, task.wait, animation) keeps the frame clock and sees frames rather than steps while an advance runs, so drive what a measurement depends on (the throttle, the brake, the load) from a step hook or fixedUpdate. While an advance runs the frame clock adds no steps of its own, so from a paused start the simulation takes exactly the steps asked; each frame runs as many as fit in frameBudgetMs of wall time (default 100), so the engine keeps drawing and answering, and an advance ends with an error if the engine leaves the mode it started in. Run it in play: the steps move bodies the way play does, and leaving play puts the scene back. Entering play starts its clock, so a measurement that needs an exact start holds it with engine.paused = true once play runs. From the shell the same is zero phys advance --seconds 12.
A measurement driven by per-frame code (a sweep that sets a vehicle's intent and reads it back with task.wait, an input-driven run, a whole match) runs faster than real time inside engine.fastForward(function() ... end) instead: every frame steps the whole game, scripts and physics together, by a fixed 1 / frameRate, and the frames run back to back. The engine guide's "How fast time passes" covers it.
Making something physical (in code)
A body is static (immovable: floors, walls), dynamic (moved by forces and gravity), kinematic (placed by your code, pushes dynamics) or kinematicVelocity (carried at the velocity your code gives it, pushes dynamics). Build one from the component primitives: give an entity a collider for its shape and a Physics component for its body.
local crate = entity.spawn("crate")
crate.position = { 0, 8, 0 }
crate.component.add("BoxCollider", {}) -- sized by the entity's mesh and scale
crate.component.add("Physics", { kind = "dynamic" }) -- static | dynamic | kinematic | kinematicVelocity
A collider alone (no Physics) is a static collider fixed in world space — the right thing for ground and walls:
local ground = entity.spawn("ground")
ground.localScale = { 40, 1, 40 }
ground.component.add("BoxCollider", {})
A dynamic body's mass comes from the space its solid colliders fill by default, at 1 kg per cubic metre, whatever the colliders' shapes: a 1 m cube weighs 1 kg, a hull around a 0.7 x 1.0 x 0.7 cylinder about 0.38 kg (a little under the cylinder's own 0.385 m^3, as the hull's flat faces cut inside its curve), and the same hull at twice the size eight times that. Set Physics.mass to a value greater than zero to pin the exact total mass instead (a value of zero or below, the default, keeps the volume-derived mass).
Either way the mass is spread evenly over the space the solid colliders fill together, and the centre of mass and inertia are that space's:
- Overlapping colliders count the space they share once. A 0.5 m box inside a 1 m box is a uniform 1 m cube, centred on the cube; a cabin box sunk into a hull box, or a ball inside a box, leans no way toward the overlap. Overlapping boxes, convex hulls and closed meshes are weighed exactly. The space two curved shapes (balls, capsules, cylinders) share is weighed over the triangles they are tessellated into, within 0.2% of the body's mass.
- A trigger weighs nothing. A collider with
isTrigger = truefills no space: a pickup radius or a proximity sphere on a body adds no mass, no inertia and no shift of its centre of mass.
Physics.bodyState(id).colliders[i].mass reports what each collider contributes: a volume-derived mass shared out over the solid colliders in proportion to each one's own volume, so the shares sum to the body's mass, and on a body whose solid colliders overlap nowhere each reports its own volume; a trigger reports 0. A pinned mass belongs to the body, so its colliders then report 0.
Who pushes whom, sleeping, centre of mass and fast bodies
The Physics component carries the settings the solver holds for each body. Every one reaches the solver on the next step when written, at add or live, Physics.bodyState(id) reads each back as the solver holds it, and a value a field cannot take is refused with an error naming the field.
dominance(-127 to 127, default 0): where two dynamic bodies touch, the one in the higher group pushes the other and is not pushed back, as if it were kinematic to it. A player character atdominance = 1shoves crates aside without slowing; a boulder at 2 rolls through both. Bodies in one group push each other as usual.canSleep(default true),sleepLinearThreshold(m/s at the body's farthest point, default 0.05) andsleepAngularThreshold(rad/s, default 0.5, read for a body with no colliders): a body that stays under its threshold for half a second falls asleep and costs nothing until something wakes it.canSleep = falsekeeps it simulated every step however slowly it moves (a probe coasting through zero gravity, a vehicle idling at a light); a higher threshold lets a pile settle and stop costing sooner.Physics.sleep(id)puts a body to sleep at once, andPhysics.wakeUp(id)wakes one.centerOfMass(local metres) andinertia(principal moments about the body's own axes, kg·m²) replace what the colliders give; leave them unset to derive them. A car body withcenterOfMass = { 0, -0.5, 0 }rights itself from a roll that tips it over with the derived centre; a weighted toy stands back up. A stated centre keeps the inertia the shape gives, andbodyStatereadslocalCenterOfMass,principalInertiaand whether each was stated.softCcd(metres, default 0): contacts are predicted that far ahead of the body each step, so a fast body is caught by a contact before it passes through a thin wall or another body, at a fraction of whatccd's sweep costs. Set it to about the distance the body covers in a step (speed / tick rate) on the bodies that are fast.
player.component.add("Physics", { kind = "dynamic", dominance = 1 })
probe.component.add("Physics", { kind = "dynamic", gravityScale = 0, canSleep = false })
car.component.add("Physics", { kind = "dynamic", mass = 1200, centerOfMass = { 0, -0.5, 0 } })
pellet.component.add("Physics", { kind = "dynamic", softCcd = 1 }) -- 60 m/s at 60 Hz
2D and 2.5D physics: holding bodies to a plane, and axis locks
A side-on game in the 3D world (a bridge builder, a platformer, an Angry Birds-like, a side-scrolling vehicle game, a side-view puzzle, a pinball table) keeps its bodies in one plane. A PlaneHold component states the plane once and holds every body it covers to it: each dynamic rigid body moves along the plane and turns only about its normal, under collisions, joints, impulses and velocities set from code, and each soft body keeps its particles on it. A body is put on the plane when the hold takes it, so a body spawned later into what the hold covers (debris, a projectile, a vehicle part, a piece torn off a soft body) is held from its first step.
-- everything under `level` stays in the XY plane, the plane of a side view
level.component.add("PlaneHold", { normal = { 0, 0, 1 }, point = { 0, 0, 0 } })
local crate = entity.spawn("crate", { parent = level, position = { 2, 4, 0 } })
crate.component.add("BoxCollider", {})
crate.component.add("Physics", { kind = "dynamic" }) -- held: no lock flags needed
- What it covers (
covers):"subtree"(the default) covers the entity's own body and the body of every entity under it;"group"covers every body whose collision membership shares a bit withgroups(a body with noCollisionGroupbelongs to every group);"world"covers every body. The nearest hold wins: a subtree hold on the body or its nearest ancestor, then a group hold, then a world hold. - Any plane:
normalandpointare world space, so a hold keeps bodies on a wall, a tilted table or the planex = 2as well as the XY plane. The solver keeps every held body's motion in its plane at each of its substeps, at any tick rate, for a few multiplications per body. - On and off at runtime: disabling the component (
level.component.get("PlaneHold").enabled = false) frees the bodies from the next step (a bridge builder's build phase), and enabling it holds them again; writingnormalorpointmoves them to the new plane. - Opting out: a hold with
free = truecovers its bodies with no plane, so a body or a subtree carrying one leaves a hold further out. - Soft bodies under a hold keep their particles on the plane; a
planetheSoftBodystates for itself stands over the hold. - Reading it back:
Physics.planeHold(id)answers{ normal, point, holder, covers }, the plane holding the body and the entity whose hold it is, or nil.Physics.bodyState(id).planeHoldandPhysics.softBodyState(id).planeHoldcarry the same.
Axis locks hold one body along world axes: lockTranslationX/Y/Z hold its position along an axis and lockRotationX/Y/Z hold its rotation about one, set on the Physics component (or with Physics.setTranslationLocks / Physics.setRotationLocks) at any time, the change reaching the solver on the next step. A locked axis holds the body still along it whatever moves it, a velocity set from code included. Locks and a plane hold combine: a body under a hold keeps its own locks, which Physics.bodyState(id).locks reads, and keeps them when the hold lets it go.
Gravity: planets, orbits, zones, and which way is down
The world has one gravity vector (Physics.setGravity, -9.81 along Y unless the world sets it), and a GravityField component adds gravity that changes from place to place: planet gravity toward a point, a pull toward an axis or a surface, a zone pulling its own way. Every dynamic body a field reaches takes it as its gravity: rigid bodies, ragdoll bones, a vehicle's chassis and soft body particles alike, inside every physics substep from where the body stands then. So a moon on a circular orbit keeps its energy and its radius: over ten orbits its energy holds within a tenth of a percent, and its radius within 1% for an orbit of a hundred steps or more (3.3 s at 30 ticks a second); a faster orbit swings a little wider about its radius (1.4% at sixty steps an orbit) without drifting off it. A slingshot past a planet bends the way it should, and a crate dropped anywhere around a small planet falls onto its surface. Where no field reaches, a body takes the world's vector.
-- a small planet a player walks all the way around, and things fall onto
local planet = entity.spawn("planet")
planet.component.add("SphereCollider", { radius = 10 })
planet.component.add("GravityField", { strength = 9.81, falloff = "inverseSquare", radius = 10, range = 80 })
-- a moon on a circular orbit 30 m out, set going on the first step: the field
-- and the moon's body stand in the physics world from the next step
local moon = entity.spawn("moon")
moon.localPosition = { 30, 0, 0 }
moon.component.add("SphereCollider", { radius = 1 })
moon.component.add("Physics", { kind = "dynamic" })
local off
off = Physics.onBeforeStep(function()
off()
Physics.setVelocity(moon.id, Physics.orbitVelocity(moon.position, planet.position))
end)
- What a field pulls toward (
shape), from where its entity stands and turned with it:"point"(a planet, a star, a black hole),"axis"(the entity's Y axis, or a segment of itlengthlong: a cylinder, a capsule),"direction"(alongdirectioninside the boxhalfExtents: an anti-gravity zone, a wall to walk on, a current),"surface"(the nearest point of the entity's own colliders, whatever shape they take: a box, a convex hull, a mesh, a terrain) and"path"(the nearest point of the line throughpoints: a spline sampled into points, a track to ride along). A field on a moving body carries its gravity with it, and leaves that body itself alone. - How strong, and how far:
strengthis the pull atradiusin m/s²;falloffis"constant","linear"(to nothing atrange),"inverseSquare"(a body of mass withradiusits surface) or"curve"({ distance, scale }points as data, for a well shaped for play rather than for Newton);rangeis how far it reaches (0: everywhere). A negative strength pushes away: a"point"field with a negative strength andrangethe shell's radius is an inverted sphere, dropping what is inside onto its shell, and an"axis"field with a negative strength is a rotating station's spin gravity. - Where fields overlap: the
"priority"fields (combine, the default) of the highestpriorityreaching a place are its gravity, summed where they share it (two planets of one priority pull a body between them toward both); an"add"field adds on top of whatever acts there (a wind, a current, a tractor beam).groupsnames the collision groups a field acts on, so a field can pull the crates and leave the players to the world's vector. A body'sgravityScalescales whatever gravity it takes. - Orbits:
Physics.orbitVelocity(point, centre)is the velocity that carries a body roundcentreon a circular orbit throughpoint, from the pull there (and anaxisto tilt the orbit); a little faster or slower makes an ellipse, and a pass close by a planet bends a body's path into a slingshot. - Which way is down here:
Physics.gravityAt(point)is the gravity at any point, exactly what the step applies there;Physics.upAt(point)is the unit up against it;Physics.gravityFieldsAt(point)lists the fields acting there, what each gives and which the point's gravity counts.Physics.bodyState(id).effectiveGravityis the gravity a body takes, after its scale. A ship hovers against any planet by pushing against the gravity where it is fromPhysics.onBeforeStep(local g = Physics.gravityAt(entity(ship).position), thenPhysics.applyForce(ship, { -g.x * mass, -g.y * mass, -g.z * mass })): the solver holds the force over the step the way it applies gravity, so the two cancel. - Characters and cameras: the Controllers library's
CharacterControllerstands, walks, jumps and falls in the frame up against the gravity where it is, so a player walks all the way around a small planet with feet toward its centre. Inside a field it carries that frame along as it walks (itsframefield), so a heading held on its input walks a straight line all the way round, the planet's far side included; itsMovementStateandLocomotionand the Controllers library'sorbital_followandthird_person_followcameras take the same up.Physics.capsuleCasttakes the axis a capsule stands along, the sweep a controller of your own makes on a planet's side, and themodules.up_framemodule turns world vectors into a frame's and back:Frame.at(x, y, z)is the frame at a point,Frame.follow(frame, x, y, z)the frame something moving keeps from one update to the next,Frame.standing(entity)the frame aCharacterControllerwalks its entity across, withFrame.toLocal,Frame.toWorldandFrame.lookAt. - Multiplayer: a field is component data, synced like any other, so every peer pulls the same way.
- Cost: while any field stands, the step evaluates the fields for every dynamic body (and soft body particle) at every substep, so it costs bodies x fields x substeps small vector sums: a few hundred bodies under a handful of fields is a fraction of a millisecond a step.
Choosing a collider
The shape is the component. Each one carries only the geometry that shape has, so there is nothing to set that means nothing.
| Component | Geometry | Reach for it when |
|---|---|---|
BoxCollider | half | Crates, walls, ground, most props |
SphereCollider | radius | Balls, blast radii, proximity triggers |
CapsuleCollider | radius, height | Characters — a rounded bottom slides over small steps |
MeshCollider | mesh, fit | The shape has to follow the model |
CompoundCollider | children | Many boxes sharing one material — a voxel chunk |
HeightfieldCollider | rows, cols, extent, heights | Terrain |
Every one also takes isTrigger, friction, restitution, rollingResistance, spinningResistance and surface (see "Surfaces" below).
Leave a dimension unset and it comes from the entity's mesh. A bare BoxCollider fits what is rendered, at any scale, and keeps fitting it when renderer.mesh.setVertices or renderer.mesh.update changes that mesh: by the next physics step the box, sphere or capsule takes the new geometry's size and centre, in edit mode and in play, and bodies asleep on it or within its reach wake. Set the dimension when you want something other than the mesh:
entity.find("crate").component.add("BoxCollider", {}) -- fits the mesh
entity.find("wall").component.add("BoxCollider", { half = { 2, 4, 0.2 } }) -- authored
Surfaces: what the ground is made of
A surface is a named material defined once as data and named on any collider: grip, bounce, how hard it is to roll or spin on, and free tags a footstep, a skid mark or an impact sound reads it by.
Physics.defineSurface("gravel", { friction = 0.6, rollingResistance = 0.04, tags = { "loose" } })
Physics.defineSurface("ice", { friction = 0.05, rollingResistance = 0.002, tags = { "slippery" } })
entity("road").component.add("BoxCollider", { half = { 50, 0.5, 4 }, surface = "gravel" })
- A collider naming a defined surface collides with its
friction,restitution,rollingResistanceandspinningResistancein place of its own fields; one naming a surface nobody defined keeps its own and still reports the name. Redefining a surface reaches every collider naming it from the next step. rollingResistancec slows a body rolling on the surface at c times gravity on level ground, whatever its mass and shape, so a ball rolled at v stops after v^2 / (2 c g): a putting green, pool cloth, a bowling lane, a sand trap are each one number.spinningResistancedoes the same for a body spinning about the contact normal (a top, a spinning ball). Both act through contacts only, so a ball in flight keeps its spin until it lands.- Per contact friction and restitution combine as they always have (the average), and the two sides' rolling and spinning resistances add: a ball of none on a floor of c rolls against c.
- Ray and shape cast hits carry
surface; contacts, their points, contact events andPhysics.contactPeakcarrysurfaceandotherSurface;Physics.groundContact(id)answers what a body stands on and the surface under it. - A
HeightfieldCollidernames a surface per height sample (surfaceLayersplussurfaceMap), and aTerraingives each painted layer the surface named after it, so a contact or a cast on painted ground names, and collides as, the layer under it. - A
WheelCollidertyre grips the surface under it: its grip coefficients are stated for ground of friction 1 and scale by the surface'sfriction(or by the tyre's ownsurfaceGripentry for that surface or one of its tags), and the surface'srollingResistanceadds to the tyre's own. So a car brakes, accelerates and corners differently on tarmac, gravel, grass and ice, wheel by wheel, with no script;Physics.getWheelState(wheel)names thesurfaceand thegroundentity under each tyre (a painted terrain's layer included).
Surfaces that act on what touches them: one-way platforms, conveyors, contact filters
Three collider fields change what a contact does inside the physics step itself, so they cost no script per contact and behave the same at any frame rate. Every collider component carries them, and each can be written at runtime. They act on the contacts the step solves: those of the bodies it moves (a dynamic Physics component, a ragdoll's bones) against the colliders that set them, and on the casts a character controller moves by (below).
-- A platform a body jumps up through and lands on.
entity("ledge").component.add("BoxCollider", { half = { 2, 0.1, 1 }, oneWay = { 0, 1, 0 } })
Physics.passThrough(crate) -- "down + jump": drop through what it stands on
Physics.passThrough(player) -- a CharacterController drops through the same way
-- A belt moving 2 m/s along its own x; a treadmill or an escalator is the same field.
local belt = entity("belt")
belt.component.add("BoxCollider", { half = { 4, 0.1, 0.5 }, surfaceVelocity = { 2, 0, 0 } })
belt.component.get("BoxCollider").surfaceVelocity = { -1, 0, 0 } -- reverse it live
-- Shots pass through their own team, coins register a touch and push nothing.
Physics.setContactFilter("redTeam", "redShot", "ignore")
Physics.setContactFilter("player", "coin", "sensor")
entity("shot").component.add("SphereCollider", { radius = 0.1, contactTag = "redShot" })
oneWayis a direction in the collider's own frame. A body moving along it passes through; a body meeting the collider from the side it points to stands on it at every speed a solid collider stops it at (a body that crosses its thickness in one step needsccd = trueon itsPhysicsto stop on either), a body resting on it stays, and each body is answered on its own, so one can jump up through a platform another stands on. A body that started through keeps passing until it is clear of the collider, then lands if it falls back. A contact whose normal leans more than 60 degrees off the direction (the platform's sides) lets the body through.Physics.passThrough(entity, through?)makes a standing body drop through every one-way collider it touches, or onlythrough's, until it is clear of each. Rotate the collider to tilt the platform, or pointoneWaysideways for a one-way wall.surfaceVelocityis the velocity, m/s in the collider's own frame, its surface moves at while the collider stays put. Friction carries what rests on it toward that velocity: a box on a belt of{2, 0, 0}with friction 0.8 on both rides at 2.000 m/s within a few steps, and writing{-1, 0, 0}carries it back at 1.000 m/s. A belt whose velocity changes wakes what rests on it.contactTagnames the collider to the world's contact filter.Physics.setContactFilter(tagA, tagB, mode)answers a pair of tags:"ignore"(they pass through each other and report nothing),"sensor"(they report contacts and contact events and push nothing) or"solid"(they collide, as every pair the filter does not name does).Physics.contactFilters()lists the entries. The filter stands beside collision groups andPhysics.ignoreCollision: a pair either of those keeps apart stays apart.- Characters and other movers. A
CharacterControllerholds no rigid body: it moves by casting rays and sweeping its capsule. Its casts are made for its own entity as their mover (Physics.raycast(origin, dir, maxDist, exclude, { mover = id }), and the sameoptionsonraycastAll,sphereCast,capsuleCastandboxCast), and a cast made for a mover meets colliders by the same three fields: a one-way collider answers it only on the face its direction points out of, to a cast that starts outside it, so the character jumps up through a platform and lands on top;Physics.passThrough(character)drops it through the one-way colliders it stands on until it is clear of each; a collider whose tag the filter answers"ignore"or"sensor"with the tag of a collider on the character (a trigger capsule with acontactTag) is passed. A dynamic body the character walks into is pushed: the walk stops at it as at a wall, and the body is given the impulse that brings its speed along the walk up to the walk's, with at most the controller'spushForce(400 N by default) behind it, so a 5 kg crate goes along at the walk with the character behind it and a 500 kg one stands like a wall (on level ground a body moves oncepushForcepasses its friction coefficient times its weight). A body that moves into the character puts it back outside, as a moving wall does.Physics.bodyOf(hit.entityId)names the body a cast hit's collider rides, its type and its mass, the read a mover of your own pushes by. Every cast hit also reportssurfaceVelocity, the collider's surface motion in world space, and the controller adds the ground's to its own walk, so a belt carries the character at its speed and a jump off it keeps that speed as momentum. A mover of your own gets all of this by passing{ mover = id }to its casts and adding the ground'ssurfaceVelocityto its motion. Characters meet one another as solid bodies: everyCharacterControllerstands as its upright capsule to every other one's wall sweep, so two characters stop a skin apart or slide around each other and readblocked; a walk moves no other character, two that overlap move apart at up to 2 m/s each, and two whosecontactTagfields the contact filter answers"ignore"or"sensor"pass through each other (Physics.setContactFilter("character", "character", "ignore")for a game where nobody blocks anybody). TheCharacterControllerREADME's "Other characters" section has the rule. The velocity verbs reach a character too:Physics.setVelocity,Physics.addVelocityandPhysics.getVelocityon an entity with no rigid body act on its mover, the component on it whose.metadatacarries thebodyMovertag (Physics.moverOfnames it; for aCharacterController, its ownsetVelocity,addVelocityandgetVelocity), so a launch pad, a spring or a knockback sends a player's character off at a speed it carries on against walls, gravity and air control; a character holds no mass, so it takes an impulse as the change of speed (addVelocity). The README's "Launching, knockback and momentum" section has the rule. A component of your own that moves a body (a vehicle, a hovercraft, a jetpack, any movement code that replaces the walking) takes all of this by carrying thebodyMovertag; "Movers" below lists what the tag gives it. - A collider with none of the three set carries no hook and adds nothing to the step. One that sets them adds a check per contact manifold it is in, about a quarter to half a microsecond each: 1000 awake boxes sliding over one floor (1000 manifolds, 4000 solver contacts) stepped 0.25 to 0.50 ms slower over a one-way floor and 0.31 to 0.53 ms slower over a moving one than over a plain floor, which took 0.78 to 1.49 ms a step, natively in the engine's development build on a loaded desktop (fastest of six rounds, three runs).
Mesh colliders and their fits
MeshCollider collides against mesh geometry, and fit chooses how that geometry is approximated:
"auto"(the default) collides as the mesh is drawn: a dynamic body takes the mesh's convex parts ("parts"), and a static or kinematic body, or a collider with no body, takes its own triangles ("exact"). A dynamic torus lets a ball drop through its hole, a dynamic cup holds what is put in it, and a static level is met triangle by triangle. It reads the body it stands on each time it is built, and a body made dynamic (itskindchanged, orPhysics.setBodyType) takes the parts in the frame that follows; a body made static or kinematic in place keeps the parts it stands on."parts"cuts the mesh's volume into convex parts (a volumetric convex decomposition) and collides as their union. It follows concavities, it is valid on a dynamic body, and a closed mesh's body weighs and balances as the solid the mesh encloses, from its first step (a mesh that does not close, or whose triangles do not all wind one way, weighs as the space its parts fill); the parts meet without a ledge between them, so a body rolls across the seam between two as over one surface. A convex mesh is its one hull.maxParts(default 32, 1 to 256) caps how many parts, andpartsResolution(default 64, 16 to 128) is how many voxels span the mesh's longest side when its volume is read: finer follows smaller concavities and costs more to cook. The cut is cooked off the frame on the worker threads, and until it lands the collider is the mesh's own triangles, weighing as the solid the mesh encloses (as its convex hull when the mesh does not close), so the body collides with its concavities and weighs from its first step: marbles put in a cup, or a ball over a torus's hole, in the same build stay in or drop through from the first step. The frame the cut lands the collider becomes its parts.Physics.bodyState(entity).colliders[i].partsreads how many parts a collider is, andpartsCookingis true while the triangles stand in. A cut of a few thousand triangles takes tens to a few hundred milliseconds on a worker and none on the frame, and every collider of one mesh at one scale shares one cook."hull"wraps the mesh in one convex hull. The cheapest to collide, and valid on a dynamic body because a hull has an interior and therefore mass. Concavities fill in: a doorway becomes a slab."exact"uses the mesh's own triangles. It follows concavities exactly, and it is for static bodies — a triangle mesh is a surface with no interior, so a dynamic body built from one has no mass and other bodies pass through it. Asking for"exact"on a dynamic body raises an error naming"parts"and"hull".
mesh names the geometry. Left unset the collider tracks whatever the entity renders; set it to collide against a cheaper proxy than the one on screen:
entity.find("rock").component.add("MeshCollider", {}) -- what you see
entity.find("mug").component.add("MeshCollider", { fit = "parts", maxParts = 16 }) -- concave, dynamic
entity.find("level").component.add("MeshCollider", { fit = "exact" }) -- concave, static
entity.find("rock").component.add("MeshCollider", { mesh = "rock_collision" }) -- cheap proxy
Identical geometry is built once and shared, so a field of a hundred of the same rock pays for one hull, and a hundred of the same mug cook their parts once.
The collider follows its mesh's geometry. When renderer.mesh.setVertices or renderer.mesh.update changes the vertices or triangles of the mesh a MeshCollider is built from, whether it names that mesh through mesh or tracks what its entity renders, the collider is rebuilt from the new geometry with no respawn, in edit mode and in play: rays, casts and bodies meet the new shape from then on, and bodies asleep on it or within its reach wake. Each changed mesh is rebuilt once per frame however many times it was written, and a hundred colliders sharing a mesh share the one rebuild. A hull, or a box, sphere or capsule sized from the mesh, is rebuilt by the next physics step; a hull of a 20,000-triangle grid costs about 1 to 2 ms there. An exact collider's triangle mesh (fit = "exact", and "auto" on a static or kinematic body) is cooked off the frame instead, on the worker threads, and the write waits for it: the mesh's new geometry is drawn, collided with and read from the frame its new collider stands, never one without the other, and no frame pays for the cook. The cook takes about 0.5 ms for 2,000 triangles and 5 to 8 ms for 20,000 on a worker, so a small mesh shows its write a frame or two later and a 130,000-triangle one about a quarter of a second later; a mesh written faster than its collider cooks shows the newest write each cook finishes for. The first build of an exact collider, when it is added, is made on the frame.
The edit is a new shape, not a moving one: it gives what touches it no velocity, and a surface moved past a body's middle in one edit leaves the body on its far side, where the contact pushes it. To carry a body, move the surface in edits smaller than half the body.
Asking whether something has a collider
The shape is the component, so there is no one component name to check for. Ask for the job instead — every collider component declares the collider role, including the superseded Collider, so this answers correctly for content authored against either surface:
if e.component.hasRole("collider") then ... end
local c = e.component.byRole("collider") -- the collider, or nil
for _, c in ipairs(e.component.allByRole("collider")) do ... end
Physics.colliderOn(id) answers the same question with the component's name, and Physics.removeCollider(id) removes whichever collider an entity carries.
Looking at what the simulation collides with
The simulation collides with colliders, not with what is drawn, and the two part company silently — a collider several times its mesh, one missing from a single tile in a row, a trigger sized as though its numbers were already world-space. None of that shows in a normal render, and reading the numbers off each entity finds only the mistakes you already suspect.
capture(pass = "physics") draws the collider set as solid shaded geometry on black, so the collision becomes a picture. Hue is what each collider takes part in — blue static, orange dynamic, green kinematic, magenta and translucent for a sensor — and lightness separates the individual objects inside a family, so two neighbouring crates never read as one shape.
capture { pass = "physics" } -- the colliders alone
capture { pass = "physics_context" } -- the colliders over the scene's meshes in dim grey
Take physics when the question is what the collision actually is: a gap in an otherwise continuous run of blue is the tile something falls through, and two colliders drawn deeply inside each other are bodies the solver will fire apart on the first frame of play. Take physics_context when the question is whether a collider sits where its model does — a collider entirely inside a mesh reads as hidden there, which is itself the answer.
Physics.colliderManifest() is the same reading as data: every collider in the world with its entity, shape type, role, and whether its geometry is the shape's true surface. Physics.colliderGeometry(opts) returns those colliders as drawable triangles for a view of your own. For the state behind the picture — mass, sleep, contacts, and why a body is not moving — see Asking what the solver holds below.
What has no collider surface to shade draws as lines over the colliders, in both views and in the edit-mode collider overlay. A soft body draws its elements coloured by load (blue slack, yellow half way, red at the load it tears), its free particles as small grey crosses, its pinned particles as green octahedra and the ones held to a rigid body as magenta octahedra, and its contacts with soft surfaces as orange segments with cyan normals: a soft body that sags, tangles or pins wrongly shows where. A WheelCollider wheel draws its suspension ray (green on ground, red in the air), its travel from the mount to the tyre's centre coloured by compression on the same ramp, its tyre circle in white, and where it meets the ground with the ground's normal: a vehicle whose wheels sit wrongly, bottom out or never touch the ground shows it.
local d = Physics.debugLines({ entities = { truck } }) -- the same lines, with the data behind them
for _, o in d.objects do print(o.kind, o.grounded, o.compression, o.pinned) end
local diag = Physics.softBodyState(body).diagnostics -- invertedCells, selfCrossings, maxLoad, loadedElements, pinned, attached
Physics.debugLines answers in edit mode too, so a soft body's cage is previewable as it is authored (a mesh body's cage follows its cellSize) and a vehicle draws its wheels at rest where they are mounted, following their authored mount, travel, radius and steering.
Composing several shapes
Colliders compose. A collider on a child entity attaches to the nearest ancestor carrying a Physics component, and each keeps its own material and trigger flag:
local body = entity.spawn("player")
body.component.add("Physics", { kind = "dynamic" })
body.component.add("CapsuleCollider", { radius = 0.3, height = 1.6 })
local head = entity.spawn("head", { parent = body.id })
head.localPosition = { 0, 1, 0 }
head.component.add("SphereCollider", { radius = 0.2, isTrigger = true })
Queries report whichever shape they hit, so the head stays distinguishable from the torso.
A body's colliders are the ones on its entity and on every entity beneath it with no Physics of its own, whichever came first: a child given a collider before its parent got Physics, or moved under the body later, joins it, and one moved out from under it stands alone as static geometry. The body's mass, centre of mass and inertia come from those shapes where they stand, so a chassis entity holding no collider, with its hull's BoxCollider on a child, turns and rolls as the hull does and has its centre of mass at the hull's centre.
A body with no collider holds none, whatever its entity renders: it collides with nothing, no body touches it, and rays and overlap queries pass through it. Physics.bodyState(id).collides reads false for it, and collisionDetail says why and names what gives it a shape. While the body's own collider is waiting to be built (a MeshCollider whose mesh is still on its way), waitingFor names what it waits for and collisionDetail says the same. It still holds the pose it is given, a joint anchored to it holds its pivot, and a dynamic one weighs the mass its Physics states (1 kg when it states none), turning with the inertia it states or, unset, with the inertia of a box of its entity's scale. A collider component added to its entity, or a collider on an entity beneath it, joins the body, and the body collides from then on. A body whose colliders beneath it are still waiting for their mesh, or sit on an inactive entity, holds none until one of them is built, and a built body whose last collider is removed or deactivated, or moves out from under it, holds none again.
Reach for CompoundCollider instead when a body carries many children that share one material. Separate components cost one broadphase entry each; a compound is one entry for the whole set, with contacts still resolved per child. That crossover is what makes a compound right for a voxel chunk and wrong for a character's head.
Soft bodies: jelly, cushions, balloons, cloth, soft models
Something that should squash, wobble, sag or drape is a soft body: give its entity a SoftBody component instead of Physics and a collider. A soft body is a set of particles held together by elastic elements, simulated in the same step as rigid bodies, so it rests on the ground, a crate lands on it and dents it, it pushes a dynamic crate it falls on, and two soft bodies stack on each other.
local jelly = entity.spawn("jelly")
jelly.position = { 0, 2, 0 }
jelly.localScale = { 1.5, 1, 1.5 } -- the body fills the entity's unit box times its scale
jelly.component.add("SoftBody", {
shape = "box", -- box | sphere | balloon | cloth | mesh
resolution = 6, -- particles along the longest edge, 2 to 24
-- mass = 0 (the default) weighs it at 1 kg per cubic metre, like a rigid body
stiffness = 300, -- Young's modulus in pascals (the default)
damping = 0.5, -- 0 rings on, 1 settles without overshoot
})
shapepicks the generator.boxandsphereare solids filled with tetrahedra;balloonis a hollow surface held out by the volume it encloses;clothis a sheet in the entity's local XZ plane. Each fills the entity's unit box (-0.5 to 0.5 on each axis) times its world scale, so a soft body sits exactly where a default cube or sphere primitive of the same scale would.massat its default of 0 comes from the shape's volume at 1 kg per cubic metre (a cloth's from its area at 1 kg per square metre), the rule a rigid body's mass follows, so a soft body and the crates around it weigh alike. A value above zero sets the total exactly.stiffnessis the Young's modulus of a box or sphere, and softness is stiffness against weight: a 1 m box at the default mass, dropped 1 m, squashes by about a sixth and wobbles back at the default 300, by about a fourteenth at 3000, and by a few percent at 30000, past which the default solver stiffens it no further; thefemsolver (Stiff materials, below) holds a body to stiffnesses far past that. A heavier body needs a proportionally higher stiffness to look the same, and one much softer than its weight sags flat and lets what lands on it slide off. For a balloon or a cloth it scales how stiff the stretch and bending springs are.preserveVolume(default on) keeps a closed shape's enclosed volume, so a squeezed jelly bulges rather than shrinking, and a balloon stays inflated.modelpicks how a solid's cells (box, sphere, mesh) resist deforming:corotational(the default) is linear elasticity of Young's modulusstiffness, stable at any stiffness;neoHookeanis the same at small strains, resists a hard squeeze more and a long stretch less, and costs about twice as much per cell;volumeis the cheapest, a jelly of springs that keeps each cell's volume, its springs scaled bystiffnessthe way a balloon's are.poisson(0 up to 0.5, default 0.3) is how much a squeezed cell bulges sideways: near 0.5 is rubber, close to incompressible.solverpicks how the body's elasticity is solved:constraints(the default) orfem, the solver for stiff materials (below). It takes effect on the running body.inflationholds a closed shape at that share of the volume it was built with: blow a balloon up to 1.5, let it down to 0.7, live (Physics.softBodyState(id).volumeRatiofollows it). It acts throughpreserveVolume.shapeMatching(hertz, default 0) pulls the body back toward its own shape as a whole: every particle is drawn toward where the best-fit placement of the body's rest shape puts it, at that natural frequency. 0 leaves the shape to the cells and springs alone; 5 to 20 keeps a soft body from folding or sagging out of its form and brings it back quickly from a squeeze, without making it stiffer to a small poke the way a higherstiffnesswould; higher pulls harder. The rest shape it pulls toward is the one the body holds at rest, so a dent that stayed (below) stays.selfContactmakes the surface collide with itself, so a cloth folded onto itself stays two layers instead of passing through.friction,restitution,collisionMemberships,collisionFilterare the surface's, as on a collider;canSleep(default on) lets a settled body sleep, which costs almost nothing per step. A body has settled once no particle has moved faster than 0.1 m/s for half a second, read from where each particle stands from one step to the next.
A soft body is its own body and its own collision surface, so it never shares an entity with Physics or a collider component: whichever is added second is refused with an error naming the conflict. The error is logged, and the refused component stays on the entity disabled, with lifecycle = "failed" and the error as its disabledReason. The material (stiffness, damping, poisson, the plastic fields below, inflation, shapeMatching, preserveVolume, friction, restitution and the collision groups) and the solver take effect on the running body when written, waking it. The other fields (shape, resolution, cellSize, collideWith, mass, model, selfContact, canSleep) are read when the body is built, so writing one rebuilds it at the entity's current transform, and the attachments are tied again on the rebuilt body. During play, a rebuild of the same particles (a new model, mass or selfContact) keeps every particle where it is, how it moves and any dent it kept.
Dents that stay: plasticity
An elastic body springs back once the load is gone. Give it a plasticYield and it keeps what it was pushed into past that strain: a car shell keeps its crash, clay keeps a print, a metal sheet keeps a crease. A part strained further than the yield has its rest shape flow toward the shape it is held in, so when the load goes it rests in the new shape.
clay.component.add("SoftBody", {
shape = "box", stiffness = 3000,
plasticYield = 0.02, -- strain past which deformation stays; 0 (the default) is fully elastic
plasticCreep = 10, -- per second: how fast the strain past the yield sets (default 10)
plasticMax = 0.5, -- the most permanent strain a part takes (default 0.5)
})
print(Physics.softBodyState(clay).plastic) -- metres: the deepest dent that stayed (plasticMean: the mean)
clay.component.get("SoftBody"):repair() -- or Physics.repairSoftBody(clay): back to the built shape
plasticYieldis a strain: 0.02 dents like sheet metal under a firm knock, 0.1 only under a hard hit. For a balloon or a cloth it is an edge's stretch and a fold's angle in radians, so a sheet keeps its creases.plasticCreepis how fast the strain past the yield becomes permanent, per second: a strain held fortseconds sets1 - e^(-plasticCreep * t)of its excess, aboutplasticCreep * tof it for a short impact. A body flows at every substep of the step on eithersolver, so a crash sets the same share of its excess at every tick rate. The default 10 keeps most of a crash's dent; 1 lets a short knock spring back and lets a steady load sink in slowly.plasticMaxbounds the permanent strain any part takes, so a body hit again and again keeps a bounded dent rather than collapsing.- A body has to hold its own weight below its yield. Its own weight strains it too, most at its bottom, and a yield below that strain lets it sag by itself, slowly, whenever it is awake. A 1 m tall block of the default mass strains about
10 / stiffnessat its base, so aplasticYieldof 0.02 wants astiffnessof 1000 or more; raisestiffnesswithmass. A body held to something that accelerates (a shell or a crash box on a car under throttle and braking) carries its mass times that acceleration through its hold as well, so keep that load below its yield too; "A car that crumples against a post or a pole" below sizes one. - The dent does not follow the tick rate.
plasticCreepis a rate per second, so the same impact leaves the same dent within a quarter at 30 or 60 ticks a second (physics.tick_rate) and at 4 or 8 substeps a tick (physics.solver_iterations): a 5 kg crate dropped on a 3 x 1 x 3 m slab ofstiffness1000 andplasticYield0.02 left a dent of 2.6 to 3.2 cm and aplasticof 2.1 to 2.2 cm across those four, and the same crate dropped from 3 m and lifted off after a second, on a slab ofplasticCreep2, aplasticof 0.96 to 1.08 cm. A rigid body that reaches a soft body within a step meets it at the part of the step it arrives in, since their contacts are predicted over the rigid body's travel in the step, so at one number of substeps a second a drop bounces alike however the ticks divide them: at 240 a second, the crate dropped from 2.9 to 3.1 m, heights spread across the 0.2 m it falls in one 30 Hz step, rebounded to 1.38 to 1.41 m and kept 0.96 to 1.03 cm at 30 ticks of 8 substeps, 60 of 4 and 120 of 2, the three drops from one height within 2 cm of each other. A faster drop keeps some of the tick in its bounce: from 8 m the crate rebounded to 1.78 m at 120 ticks of 2 and 1.93 m at 30 of 8. A body withccdset takes no such prediction in a step its continuous sweep covers, and there its bounce follows the part of the step it first touches in: the same crate withccddropped from 2.94 to 3.03 m rebounded to 1.39 m at 60 ticks of 4 and to 1.49 to 1.60 m, or not within a second, at 30 of 8. The body's elastic give does follow the substep (the tick divided by the solver iterations): at the default 1/120 s a body gives about a quarter more under a steady load than at 1/240 s or shorter, and a steady load holding a part just past its yield with a slowplasticCreep(1 or less) sets its dent about twice as fast at 1/120 s as at 1/240 s. Tune a world's plastic bodies at thephysics.tick_rateandphysics.solver_iterationsit runs at. - Repairing (
:repair(),Physics.repairSoftBody(id), or raising the component'srepairscount, which reaches every peer) restores the shape the body was built in: the body is put back in it where it stands, moving on as it moved. Leaving play for edit mode also puts every body back in its built shape, and edit mode builds bodies in that shape. - The drawn model keeps the dent. A
Modelon the body is bound to the shape it was built in, so a dent shows on the model as deep asplasticreads, and a model with more vertices shows it more finely. - A body rebuilt during play with the same particles (a new
model,massorselfContact, or its entity moved while the clock is paused) keeps the deformation that stayed. A rebuild of other particles (a newshape,resolution,cellSizeor scale) starts from the generator's shape.
While the simulation runs, the entity's position and rotation follow the body as a whole (the rigid motion that best fits its particles), so children, scripts and tools that read the entity see where the body went. A Model on the entity is drawn deformed with the body: every vertex of the model rides the body element nearest it at rest (a tetrahedral cell of a box or sphere, a surface triangle of a balloon or cloth), so a dent, a squash or a drape shows on the model itself, with its own material, and lighting, shadows and motion vectors follow the deformed surface. The model is drawn between physics ticks the way a rigid body's pose is, culled against the box its deformed vertices stay inside, and a cloth's model draws both faces of its sheet. Nothing extra is needed: add SoftBody to an entity that has a Model. The model's vertices decide how finely the deformation shows (a 24-vertex cube primitive can only move its corners), so give a soft body a model with enough vertices to carry the shape. Physics.softBodyState(id).render reads the render side back: whether the frame drew the model deformed (drawn), how many vertices and elements are involved, whether the frame uploaded anything (uploadedThisFrame; a body at rest costs no upload) and the world-space bounds it is culled against. The physics view (capture with pass = "physics") draws the collision surface itself, for comparison. Writing the entity's position or rotation during play carries the body there, shape and velocity kept; in edit mode, where nothing simulates, the body is rebuilt in its rest shape where you put it. Deactivating the entity, removing the component or despawning the entity removes the body. Editing the SoftBody component's code (a hot reload) keeps it: the reloaded component takes the body over as it stands, its dents, motion and pins included.
Tuning a deformable by numbers: energy, stability and measured response
Three reads tell an author what a soft body does with a load, so a material is tuned toward "takes X kJ over Y m" by numbers rather than by watching it go wrong.
Where the energy went. Physics.softBodyEnergy(id, { mark = true }) starts a body's energy ledger; read it again (Physics.softBodyEnergy(id)) after a drop, a crash or a crush:
Physics.softBodyEnergy(shell, { mark = true }) -- before the crash
-- ... the crash ...
local e = Physics.softBodyEnergy(shell) -- every value in joules
print(e.absorbed, e.plastic, e.fracture) -- taken by plastic flow and tearing since the mark
print(e.kinetic, e.elastic) -- what it holds now
print(e.gravity, e.dissipated, e.departed) -- gravity's work; lost otherwise; carried off by torn pieces
for _, r in e.regions do print(r.name, r.absorbed) end -- a crumple zone's share
The ledger balances: atMark.kinetic + atMark.elastic + gravity = kinetic + elastic + absorbed + departed + dissipated. elastic is the energy the body's elements store for the shape they hold (an edge, for the force the solver gave it), plastic the work its plastic flow took (an element's stored energy before the flow less after it, an edge's force times the way its rest length moved), fracture the energy the elements a tear or a cut took out held, and dissipated everything else the body lost: damping, friction, contact, and the solver's own losses in a hit faster than its substeps follow, less the work whatever holds or pushes the body did on it (an attachment, a pin, a press), so a body a chassis drives reads that drive as negative. peakAcceleration is the largest acceleration of the body's centre of mass over one step since the mark. A body is accounted after every step that moves it once it is marked (costMs is what the last step's accounting of it took: about a quarter of a millisecond for a box of 125 particles); a body never marked costs nothing, and reads only kinetic and elastic with accounted = false. Mark again to start over. On the fem solver the elastic energy reads the work a slow press put into a body within 3%; the default solver holds a cell somewhat softer than its material, so there a pressed body's elastic reads about a sixth above the work the press did.
Whether the solver holds it. Physics.softBodyState(id).stability compares the body's stiffest elements with the rate the solver runs them at, as soon as the body is built and before it steps: substepHz (the physics.tick_rate the world's settings state times its physics.solver_iterations, in edit mode as in play), parts, each element family (cells, edges, bends, folds, volume cells, volume, and cells of region crumple for a region's material) with the highest natural frequency of its elements (hz), that over substepHz (ratio) and whether the solver holds it at the stiffness it states (holds). The default solver holds an element that rings no faster than its substeps; a stiffer one it holds softer than stated, and far past it, it jitters and comes apart. holds is false and cannotHold names each part with its numbers when one is past it. It reads the material against the substeps, not the load: a hit the body takes within a step or two (a fast landing on a soft pad) is resolved only as finely as the step, and measureSoftBody reads its peak deceleration averaged over the step, so count the samples that carry force and raise physics.tick_rate to see its shape:
local st = Physics.softBodyState(cube).stability
if not st.holds then print(st.cannotHold[1]) end
-- a 1 kg, 1 m cube of stiffness 1e7 at resolution 6, at 30 ticks and 4 iterations:
-- "cells: 625 element(s) ring at up to 2247 Hz, 18.7 times the 120 substeps a second the solver runs them at, so it holds them softer than they are stated"
A 1 kg, 1 m cube at resolution 6 reads a ratio of 1.0 at a stiffness of 30000, past which the default solver stiffens it no further (the soft body figures above), and 0.84 at 20000; the 2 m beam of "Stiff materials" below reads 12.9 at stiffness 1e8, where it hangs from its pin and swings on the default solver, and 40.8 at 1e9, where it flies apart. Lower the stiffness, raise the mass, raise physics.tick_rate or physics.solver_iterations, or move the body to solver = "fem", which integrates every element implicitly and holds any of them. An element of a custom body with no stiffness of its own is held as stiff as the solver holds anything (1000 Hz) and reads past the substeps: give a load-bearing member a stiffness that rings below them (√(k (1/m_a + 1/m_b)) / 2π hertz for a member between particles of m_a and m_b kg) so the solver holds it.
How it responds to a stated load. Physics.measureSoftBody(id, test) builds a copy of the body from its component as authored (shape, material, regions, in the shape it was built in) in a world of its own, at the tick and solver iterations the world's settings state (physics.tick_rate, physics.solver_iterations, read in edit mode as in play), puts a stated load on it, and samples every step: the load (force, newtons) against how far it pushed the body (displacement, metres), with the body's kinetic, elastic and absorbed energy. samples holds one array per quantity, one entry per step: for i = 1, m.steps do print(m.samples.displacement[i], m.samples.force[i]) end. The live body is untouched, and the call answers in edit mode as well as play mode, in the same call that added the component too (a body not built yet is measured as its component builds it at the entity's pose and scale; a mesh body waits for its model's fill). Every measurement carries stability, the measured copy's stability report at the rate it ran, which is how a body added in the same call reads one before Physics.softBodyState(id).stability is there.
-- pressed between two frictionless plates along its own y axis, 3 cm at 2 cm/s
local m = Physics.measureSoftBody(block, { press = { depth = 0.03, speed = 0.02 } })
print(m.stiffness, m.peakForce, m.work, m.absorbed, m.permanentSet)
-- driven at 15 m/s into a post 0.2 m across, carrying 700 kg held to its trailing face
local m = Physics.measureSoftBody(nose, { impact = { speed = 15, radius = 0.1, carried = 700 } })
print(m.crush, m.rebound, m.absorbedShare, m.peakDeceleration / 9.81)
-- dropped 2 m onto a floor
local m = Physics.measureSoftBody(crate, { drop = { height = 2 } })
print(m.absorbed, m.elastic, m.dissipated, m.gravityWork)
press = { depth, axis?, speed?, hold?, settle?, friction? }presses the body along its ownaxis("x","y"or"z", with a sign, default"y") todepthmetres atspeed(defaultdepthover 2 s), holds itholdseconds (0.5), withdraws the plate at that speed while the body still pushes on it, then stands it clear and lets the bodysettle(1 s).displacementis how much shorter the body stands between the plates;stiffnessis the initial slope of the load against it (over the first fifth of the depth),workthe area under the loading curve andreturnedwhat the body gave back as the plate withdrew,permanentSethow much shorter it stands once it settled. The plates are frictionless unlessfrictionsays otherwise, so an elastic block reads its material'sE A / L(AandLthe section and length of the block its particles span, its contact skin left out): a 1 m cube ofstiffness1e5 at resolution 6 withpreserveVolume = falseread 75000 N/m on the default solver and 82000 onfemagainst 80000. The plates are the only thing that works on the body, sodissipatedis the work less what it absorbed, holds and moves with.impact = { speed, direction?, radius?, offset?, carried?, duration?, friction? }sends the body atspeedalong its owndirection(default"-z", the way a chassis drives) into a post ofradiusmetres standing across it, or a wall whenradiusis left out (offsetmoves the obstacle off the body's centre), fordurationseconds (1.5).carriedkilograms ride behind it on a rigid block held to its trailing face, meeting the obstacle only once the body has crushed out of the way: the frame a crumple zone protects. It reportscrush(how far the block, or the body's centre of mass, travelled past where the body met the obstacle),peakForce,peakDeceleration(m/s²),rebound(the speed it ends moving back at),energyIn,absorbedShareand, with a carried block,carriedStruck(whether the block reached the obstacle).drop = { height, duration?, friction? }drops itheightmetres onto a floor under the world's gravity and reports the same as an impact, withgravityWork.
The measurement runs synchronously; a box of a few hundred particles through a 1.5 s impact takes tens of milliseconds, a fem body more.
Stiff materials: the FEM solver
The default solver holds each elastic element as a constraint and sweeps them all with the contacts a few times a substep. That is cheap and right for jelly, cushions and crumpling shells, but it converges only as far as its sweeps reach: a stiff body (a steel or plastic beam, a chassis rail, a panel of stiffness 1e6 and up) keeps more give than its material has, a load crossing a long body takes several steps to reach its far end, and past a point the sweeps jitter and the body flies apart. solver = "fem" solves the whole body's elasticity at once each substep (implicit finite elements), so a stiff material holds the shape its stiffness gives it and a load reaches across the body in the step it lands.
-- a 2 m beam held by one end: it stands out straight on "fem" and swings from its pin on "constraints"
beam.localScale = { 2, 0.2, 0.2 }
beam.component.add("SoftBody", {
shape = "box", resolution = 16, stiffness = 1e8, mass = 8, damping = 1,
solver = "fem",
pins = { { name = "root", region = { box = { min = { -0.5, -1, -1 }, max = { -0.45, 1, 1 } } } } },
})
print(Physics.softBodyState(beam).solver) -- "fem"
That beam, measured on native and in the browser: on fem its tip hangs 3 cm below where it was built and holds still, the same on both; on constraints at the same stiffness it hangs from its pin and swings, its tip half a metre to 1.7 m down and still moving at 1 to 4 m/s five seconds on. At stiffness 1e9 the constraints beam flies apart within a few seconds and the engine switches it off, while the fem beam stands 3 mm below where it was built and holds still. Everything else works on it as on the default solver: contacts with rigid and soft bodies, attachments, pins, the plastic fields, tearing and cutting (a piece torn or cut off a fem body stays on fem), and sleep. A Joint on a region of a fem body is answered through the whole body, so the beam above held by a fixed Joint on its root face instead of the pin stands out the same way, its tip 3.7 cm down.
Choose it for the parts that must hold their shape (a beam, a frame, a stiff panel, a bumper) and keep the default for everything soft. What it costs, one awake body resting on the ground (or the beam above, held in the air by its pin), stiffness 1e6, in milliseconds: the median soft body time of 40 steps once the body settled, measured twice on a busy machine, natively and in Chrome:
| body | particles | cells | constraints, native | fem, native | constraints, browser | fem, browser |
|---|---|---|---|---|---|---|
the beam above, stiffness 1e8 | 144 | 300 | 1.0 | 0.9 | 1.1 to 1.2 | 1.1 to 1.2 |
| box, resolution 4 | 64 | 135 | 0.3 to 0.4 | 0.5 to 0.6 | 0.5 | 0.8 |
| box, resolution 6 | 216 | 625 | 1.1 to 1.5 | 4.9 to 6.3 | 1.7 to 1.8 | 6.5 to 6.8 |
| box, resolution 8 | 512 | 1715 | 2.9 to 4.6 | 34 to 36 | 4.6 to 4.8 | 38 to 41 |
A fem body costs by its particles and by what touches it: each contact and attachment on it is answered through the whole body, so the resolution-6 box resting on a face of 36 particles costs five times the beam held by its end, with only half again its particles. Hold fem bodies to resolution 6 or below and to the few parts that need it: a resolution-8 box alone takes twice the 16 ms a frame at 60 frames a second has.
Three world settings tune how far the solver goes each substep, read and written with Physics.softBodySettings like the others:
femMaxDenseDofs(default 1600, a resolution-8 box): the largest body, in degrees of freedom (three per particle), whose system is factorized directly at the start of each step. The factorization answers the contacts and attachments on the body and carries each substep's solve to convergence in a few iterations. A larger body is solved iteratively instead, which converges a stiff body only withfemMaxIterationsin the hundreds. The factorization is the cheaper step up to resolution 8 (a resolution-6 box steps in about 5 ms factorized and 13 ms iteratively, a resolution-8 box in 35 ms and 43 ms) and the dearer one past it (a resolution-10 box, 3000 degrees of freedom, in about 180 ms factorized and 140 ms iteratively).femMaxIterations(1 to 1000, default 20): the most iterations a substep's solve runs. A body factorized directly needs a few; a larger stiff body solved iteratively and cut short behaves softer than its material, the way the default solver does.femTolerance(above 0 and below 1, default 1e-5): the residual, relative to where it started, at which a solve stops.
A soft version of a model
shape = "mesh" makes the entity's own model soft: an imported character, a rubber duck, a pudding, a car body. The body is the model itself, filled with tetrahedra (its cage), and the full-detail model is drawn carried by the cage, seams and UVs intact.
-- `duck` already draws a closed model
duck.component.add("SoftBody", {
shape = "mesh",
cellSize = 0.08, -- metres; 0 (the default) is the model's longest extent / resolution
collideWith = "cage", -- or "surface": collide through the model's own surface
})
-- the body is built at the start of the next frame; once `status == "built"`:
local s = Physics.softBodyState(duck)
print(s.cellCount, s.particleCount, s.cage.cellSize, s.cage.cached, s.cage.buildMs)
-- also: s.cage.filledParts, strayParts, openParts, seams, pieces, generateMs, digest
- The model must enclose a volume. Every closed part of it (each edge bordered by exactly two triangles) is filled at the entity's world scale; vertices split for UVs or normals are joined first, and a part wound inside out is turned. A part that is open or non-manifold, or too small to hold one cell, is left out of the fill and counted (
cage.openParts,cage.strayParts), and is still drawn carried by the cells nearest it. A model with no closed part is refused, naming the edges at fault. cellSizeis the edge of the cells. Smaller follows the model's outline more closely and costs more to build and to step; the cells always contain the model, so a coarse cage is blocky but never cuts into it. Halving the cell size makes about eight times the cells, and the step cost follows the particles: a cage of a few thousand cells steps in milliseconds, one of tens of thousands takes a large part of a frame or more. Start from the default (cellSize0: the model's longest extent overresolution, 6 cells by default), readparticleCountandPhysics.stepCost().softBodyMs, and refine only as far as the look needs; the model is drawn at full detail whatever the cell size. A size that would make more than 60000 cells is refused before anything is built, naming the smallest size that fits.collideWithpicks the surface the body meets the world through:cage, the boundary of the cells (cheap, as coarse ascellSize), orsurface, the model's own closed surface carried by the cells (as fine as the model). A contact on the surface pushes the cell holding the touched triangle, or, for a triangle spread over several cells, the cell holding its nearest corner, sosurfacesuits a model whose triangles are no larger than the cells; a model of a few large flat faces meets the world more evenly throughcage. Either carries a contact skin of 0.15 of a cell (particleRadius): the drawn model of asurfacebody rests that far above what it stands on, and acagebody's at least twice that, since its cells wrap the model no closer than the same distance.- The cage is made once. Cages are kept by the model's triangles, the scale and the cell size, so a second instance of the model, a rebuild at the same scale and a switch between edit and play take the cage already made:
cage.cachedis true andcage.buildMsis 0 (cage.generateMsis what making it cost). The fill is the same on every platform:cage.digestnames the cage, equal for equal input. The cage is derived from the model and never written into the scene. - Parts that touch move as one. A model built of several closed pieces (a car body and its doors, a beam resting on two posts) is split where one surface only touches another, each piece is filled on its own, and pieces whose cages meet are sewn together with springs (
cage.seams), so they deform and move as one body. Pieces further apart than half a cell stay separate (cage.piecescounts them).
The deformation itself is read from the solver:
local s = Physics.softBodyState(jelly)
print(s.particleCount, s.cellCount, s.volumeRatio, s.sleeping) -- volume / restVolume
print(s.bounds.min.y, s.centerOfMass.y)
for _, p in Physics.softBodyState(jelly, { positions = true }).positions do
-- every particle, in world space
end
status says where the body stands. The body is built at the start of the frame after its component is added, so a read in the same call as component.add answers status = "pending" with exists = false, and waitingFor names what the build waits on: the build at the start of the next frame, a mesh body's model still loading, or the entity being active in its hierarchy. status = "refused" with refusal says why a SoftBody component was not built (a conflicting Physics, a field out of range, a model that cannot be filled), "built" means the solver holds it, and "none" that the entity carries no SoftBody. Wait on the status rather than reading exists = false as a refusal:
jelly.component.add("SoftBody", { shape = "box", resolution = 4 })
print(Physics.softBodyState(jelly).status) -- "pending": built at the start of the next frame
-- a frame later: "built"
The surface the body collides through is an ordinary collider to the rest of the physics surface: rays and overlaps hit it and name the soft body's entity, contacts on a crate resting on it names the soft body, Physics.colliderGeometry() and the physics capture view draw it deformed as simulated, and worldState().softBodies counts soft bodies on their own.
A ray or a shape cast that hits a soft body meets its surface as it is deformed now, and its hit names where on the body it landed as hit.softBody: the surface triangle (element), the particles carrying it with the hit's share on each (particles, weights), the particle nearest the hit (particle), and region, the hit as a soft region. A hit is answered at the spot it struck in one step, a dent where a shot lands:
local hit = Physics.raycast(muzzle, aim, 100)
if hit and hit.softBody then
Physics.applyImpulseAtPoint(hit.entityId, { x = 0, y = 0, z = -20 }, hit.point, { radius = 0.3 })
end
Physics.contacts and Physics.touching work with a soft body on either side, two soft bodies included, and a contact with a soft body names the particles of it that are touching (particles for the body read, otherParticles for the other side), numbered as Physics.softParticles numbers them. Physics.contacts(truck, pole) reads that one pair. A soft body resting on the ground holds a contact point per surface element touching it, so a read of every pair a large body is in costs every one of those points.
What a soft body costs, and the settings that trade quality for it
A soft body costs the solver its elements (cells, edges, folds) and the contact points on its surface, each solved once per substep, so the cost grows with the particle count: a cube at resolution 6 is 216 particles, at 8 it is 512. resolution counts the particles along the longest side; a shorter side takes round((resolution - 1) * side / longest) + 1, at least 2. The count jumps where that rounding does: a 1.8 x 0.8 x 4 m truck shell at resolution 8 is 4 x 2 x 8 = 64 particles, a 1.9 x 0.9 x 3.8 m one is 5 x 3 x 8 = 120. Physics.softBodyState(id).particleCount reads the count a body was built with. Read what each body costs from the step that just ran:
local c = Physics.stepCost()
print(c.softBodyMs, c.softBodiesAwake) -- the soft body part of the step, and how many bodies it simulated
for _, b in c.softBodies do -- costliest first
print(b.entity, b.ms, b.particles, b.cells, b.contacts, b.substeps)
end
print(Physics.softBodyState(jelly).lastStepMs) -- one body's part; 0 while it sleeps
softBodyMs is the step's soft body time: the step is timed as a whole, and softBodyMs is the part of it in proportion to the elements the soft bodies handed the solver against the rigid contacts and joints (softBodyShare). softBodies divides it between the bodies by the work each handed the solver; a body asleep is not listed and costs nothing. A body's ms is its share by work rather than a clock of its own: bodies that hand the solver the same elements, contacts and substeps (four identical trucks in a symmetric crash) read the same ms, and contacts says which body is pressed hardest. substeps is the world's solver iterations plus the extra ones a body asks for while it is hit fast or loaded hard; bodies touching each other share an island, which runs the most any of them asks for.
A frame can run more than one step (the tick is fixed, the frame rate is not), and stepCost breaks down the last of them. recent lists the last 64 steps, oldest first, each with its ordinal step and its stepMs, softBodyMs and softBodiesAwake, so a loop that reads once a frame still counts every step:
local seen, steps, total, worst = 0, 0, 0, 0
task.spawn(function()
while steps < 600 do -- ten seconds at the default 60 Hz tick
local c = Physics.stepCost()
if c then
for _, s in c.recent do
if s.step > seen then
seen = s.step
steps += 1
total += s.softBodyMs
worst = math.max(worst, s.softBodyMs)
end
end
end
task.waitFrames(1)
end
print(("soft body time: %.1f ms a step on average, %.1f ms at worst"):format(total / steps, worst))
end)
Keeping up with real time
Each frame the gameplay clock runs adds the frame's seconds (times engine.timeScale) to what the world owes, and runs a step for every 1 / tickRate of it. A frame catches up at most maxCatchUpSeconds of simulated time (0.25 by default): a frame that owes more drops the rest, so a long stall (a hitch, a debugger pause, a world loading) does not come back as seconds of fast-forward. The bound is a time, so a world keeps real time on the same frames at every tick rate: at 240 steps a second a 100 ms frame runs 24 steps, as a 30 a second one runs 3.
A frame always runs its first step, and never more than maxSubsteps (1000 by default). Past the first it runs a step only while its steps keep pace with the time they cover and have taken no more than a quarter of the frame's wall time or 1/60 s, whichever is more. So a world whose steps are cheap catches up the whole bound, and a slow frame (a heavy scene, a slow device) runs a few steps, which come to at most about a third of the rest of the frame, while a frame drawn near 60 fps that owes two steps runs both: the scene keeps the frame rate its own work allows and runs in slow motion, where catching up every step would lengthen each frame, and with it the time the next one owes, until the frame rate fell to a fraction of that. Lower maxSubsteps to cap the steps any frame runs; lower maxCatchUpSeconds to bound how much any frame catches up. A frame of a fixed-step take (a recording on the frame cadence) runs every step it owes up to maxSubsteps, whatever the wall clock reads.
Physics.catchUp() states how the clock kept up: the frames it ran, the frames that dropped time (framesAtBound), those of them that stopped stepping with whole steps still owed (framesBehind: at maxSubsteps, or with steps that fell behind the time they cover or took their share of the frame), and the simulated seconds they dropped, counted since the engine started, so the difference of two reads covers the frames between them. boundSeconds is the bound in force. Read it to choose a tick rate: a rate whose frames drop time on the frames the engine draws runs in slow motion, and frames that fall behind say the steps cost more than the frame leaves them.
Physics.solverSettings({ tickRate = 240 })
local before = Physics.catchUp()
task.wait(2)
local after = Physics.catchUp()
print(("%d of %d frames dropped time (%d fell behind), %.2f s dropped (bound %.3f s)"):format(
after.framesAtBound - before.framesAtBound, after.frames - before.frames,
after.framesBehind - before.framesBehind,
after.droppedSeconds - before.droppedSeconds, after.boundSeconds))
profiler.counters("physics.catch_up_*") counts the same per frame: physics.catch_up_frames_at_bound (1 for a frame that dropped time), physics.catch_up_frames_behind (1 for a frame that stopped stepping with whole steps still owed) and physics.catch_up_dropped_us (the microseconds it dropped).
The figures are wall-clock milliseconds, so anything else on the machine competing for the core (another engine, another agent's work, a build) lands in them as a slow step that nothing in the scene caused. Compare two settings on the median and the 95th percentile of the same scene run more than once, and take a single slow step as the scene's own only when it lines up with an event in it (the step softBodies lists the most contacts on, a body built during play).
Measured cost of one awake body per step, falling and landing on ground, the cost of its elements with a few contacts (two soft bodies pressed into each other cost by their contacts as well, which softBodies lists per body) (native engine; the lowest step of 40, which is the cost without other work on the machine competing for the core; the mean on a busy machine runs 1.5 to 3 times that):
| body | particles | cells | ms per step |
|---|---|---|---|
| box, resolution 4 | 64 | 135 | 0.2 |
| box, resolution 6 (the default) | 216 | 625 | 0.4 to 0.7 |
| box, resolution 8 | 512 | 1715 | 1.2 to 1.6 |
box, resolution 6, model = "neoHookean" | 216 | 625 | 1.0 to 1.3 |
box, resolution 6, model = "volume" | 216 | 625 | 0.7 to 0.9 |
| sphere, resolution 6 | 331 | 1272 | 1.0 |
| balloon, resolution 6 | 162 | 0 | 0.5 to 0.65 |
| cloth, resolution 12 | 144 | 0 | 0.2 |
The cells of a box, a sphere or a mesh fill on the default model (corotational) are solved four at a time, and a cell whose rest shape, particle masses, material and substep length are the same as on the last step reuses that step's setup, which is why they cost less per cell than the neoHookean and volume cells beside them.
A body cut finely enough to dent as narrowly as what hits it costs by its cells. A 1.8 x 0.8 x 4.4 m shell at resolution 24 (1200 particles, 4140 cells, about 0.2 m between particles), held by its floor to a 600 kg chassis and driven at 50 km/h into a static post 0.2 m across, took 3.1 to 3.4 ms of soft body time at its cheapest step, the cost with nothing else competing for the core, at 30 and at 60 ticks a second; over the 4 s from the start of the drive it averaged 5.7 to 10.2 ms a step at 30 ticks a second and 6.1 to 9.6 ms at 60, with its worst step at 13.6 to 36.8 ms, on a machine running three to five times the work it has cores for. At resolution 16 (448 particles, 1350 cells) the same crash took 1.1 to 1.2 ms at its cheapest step and averaged 2.1 to 2.5 ms on that machine. Every step of the drive costs about the same as the step of the hit, so a scene of several such bodies pays for each body's cells on every step it is awake. At stiffness = 20000 and plasticYield = 0.02 the post left a dent 0.67 to 0.75 m wide (the span over which the front's permanent set is at least half its deepest) and 6 to 9 cm deep at 30 ticks a second, and 0.9 to 1.2 m wide and 10 to 14 cm deep at 60.
A body moving fast past something off its path costs nothing for it: the reach a soft body's surface is checked against over a step is where its particles travel over that step, along each axis, so what lies beside or behind that travel is never paired with it. The shell above, driven along the road with 0.3 m of air under it, lists no contact with the road in stepCost().softBodies and runs the world's solver iterations, so cruising costs its cells alone.
What a body rests on costs about the same whether it is built from boxes, a triangle mesh (an exact MeshCollider) or a heightfield, however finely the mesh is cut: each element of the soft surface meets the triangle closest to each of its corners and the few reaching into it between them (a bump, a ridge, a spike), so the contact points stay at a few per surface element. The sphere above (resolution 6, scaled to 0.8 m), dropped from 1.2 m into a 1536-triangle exact bowl whose triangles fan into its bottom, cost 2.1 to 2.5 ms a step on average over the 150 steps from its drop and 12.5 to 14.5 ms at its worst, its pairs holding at most 2400 to 2800 contact points; dropped into the same bowl built from 33 boxes it cost 3.1 to 4.7 ms on average and 10 to 15 ms at its worst. Woken at rest with a light Physics.applyImpulseAtPoint, it cost 4.7 to 6.0 ms a step on average over the next 90 steps in the mesh bowl and 5.3 to 5.7 ms in the box bowl (native engine, every step counted, twice each, on a busy machine).
The material options cost by what they add to each step, measured the same way in one session, twice, beside the plain bodies they change, on native and in the browser (on a busier machine than the table above, where the plain resolution-6 box read 0.7 to 1.0 on native and 0.6 in the browser):
| body | particles | cells | ms per step, native | browser | the same body without it, native | browser |
|---|---|---|---|---|---|---|
box, resolution 6, stiffness 1000, plasticYield = 0.02 | 216 | 625 | 1.2 to 1.3 | 1.0 | 0.4 to 0.6 | 0.5 |
box, resolution 6, shapeMatching = 20 | 216 | 625 | 0.8 to 1.0 | - | 0.7 to 1.0 | - |
balloon, resolution 6, inflation = 1.5 | 162 | 0 | 0.3 to 0.4 | 0.4 to 0.5 | 0.3 to 0.4 | 0.4 |
cloth, resolution 12, selfContact = true | 144 | 0 | 0.5 | 0.5 | 0.2 | 0.2 |
Plasticity costs a body only while it flows: a cell strained past its yield flows at every substep and is solved against its new rest shape for the substeps still to come, so the plastic box, which flows as it lands, costs about twice the plain one, while a body within its yield pays a check of its strain a substep and a body with no plasticYield nothing. Inflation adds nothing measurable: it only changes the volume the body is held at. Shape matching adds a pull per particle and stays within the spread of the plain box. Self contact is the one to budget for: a self-collision pass over the surface each step, about two and a half times a cloth's cost.
At 30 Hz the tick is 1/30 s (33 ms; 17 ms at the default 60 Hz), and the soft bodies awake at once share it with everything else a step does. The budget to hold a scene to is half the tick: about 16 ms of soft body time a step on average, which leaves the other half to the rigid bodies, the scripts and the frame. Four default boxes and a cloth all dropped at once (1008 particles) cost 5.0 to 6.6 ms of soft body time a step on average over the 60 steps after they are built on native and 9.9 to 13.1 ms in the browser, and 15 to 52 ms on the steps they land on (every step counted, twice on each, on a busy machine); once they settle they sleep and cost nothing. On the scenes measured here the browser ran at up to about 2.5 times the native soft body time, so a scene held to about 8 ms on native stays inside the budget in the browser. Lower the resolution or pick model = "volume" before anything else, and let settled bodies sleep: a sleeping body is not solved, so twenty settled boxes read softBodyMs 0 and the whole step 0.06 ms at the median (native engine, twice).
The world-wide settings trade simulation quality for cost on every soft body at once. They are world settings, saved with the world in .world_settings (physics.soft_body_*), and Physics.softBodySettings reads and writes them:
print(Physics.softBodySettings().maxExtraSubstepRate) -- 120
Physics.softBodySettings({ maxExtraSubstepRate = 60 }) -- cheaper hard hits
Physics.softBodySettings({ tangleDetection = false }) -- skip the tangle search
maxExtraSubstepRate(0 to 1920, default 120): the most extra substeps a second a body hit fast or loaded hard adds to its island. A body hit fast asks for enough substeps that nothing at its contacts moves more than a particle's radius in one, and a body pressed hard (past 20 g of contact load for its mass) for 300 substeps a second, 360 past 60 g. A step adds at most this rate over its length, rounded down to whole substeps: at 120, 4 extra a step at 30 steps a second, 2 at 60, 1 from 61 to 120 and none above 120, so a hit is solved at up to 240 substeps a second at each of 30 x 4, 60 x 2 and 120 x 1, and at the 240 a world stepping at 240 x 1 already runs. Between 120 and 240 steps a second the rate allows less than one extra substep a step, so a world stepping at 144 x 1 solves a hit at its own 144 substeps a second; raise the rate to the tick rate (144) for one extra substep a step there. A 100 kg crate thrown down at 20 m/s onto a resolution-4 soft box has the box run 8, 4, 2 and 1 substeps a step on the hit at those four rates (native engine, twice). Each extra substep solves the body again; 0 holds every body to the world's solver iterations, and a fast hit then sinks deeper before the contact holds it. The extra substeps last as long as the body is hit fast or pressed hard.contactStiffening(default 4): how much stiffer soft contacts are than rigid ones.resweepStrain(default 0.75, 0 turns it off): the strain past which a body's elements are solved again after each substep's contacts, so a light body under heavy ones is not torn. Each re-solve is another pass over the strained elements, so in a pile-up 0 cuts the costliest steps; watch the bodies'volumeRatiofor one crushed out of shape under a heavier one.tangleDetection(default true): each step looks for cells turned inside out and surfaces passing through themselves or each other, and lets the elasticity undo them. Off saves that search on scenes where nothing tangles; where soft bodies pile into each other (a crash), bodies left passing through each other keep every contact of the overlap, and that costs more than the search saves.overlapConstraints(default true): closed soft surfaces that overlap something are pushed apart by the volume of the overlap. Off leaves an overlap to the per-point contacts alone, which in a pile-up hold the bodies interpenetrated.recoveryPace(default 0.5): metres per second a tangle or an overlap is undone at.
A field the settings do not have, or a value out of range, is refused by name. The solver runs under a change from the next tick. Written during play, the settings land on the play shadow like any other /source write, so a discard of the play edits takes them back (and the solver with them); write them in edit mode, or keep them with vfs.promotePlayShadow("/zero/source/.world_settings"), for the world to keep them.
A body built from more cells than one body may hold is refused before anything is built: resolution past 24 names the range, a sphere filled with more than 60000 cells names the highest resolution that fits, and a mesh fill past 60000 cells names cellSize and the smallest size that fits.
Holding a soft body to a rigid body: flags, panels, car shells
A region of a soft body can be held to a rigid body: a flag's edge on its pole, a soft panel or a whole body shell on a car's chassis, a jelly glued to a moving platform. The hold is two-way: the region follows the rigid body wherever it goes, and the rigid body carries the region's weight and feels it pull, so a cloth hung from a dynamic pole drags it down and a shell on a chassis adds its mass to the car. The rest of the soft body stays soft: it sags, flutters, and dents where it is hit.
-- a flag hanging from a pole by its top edge
local pole = entity.spawn("pole")
pole.position = { 0, 4.6, 0 }
pole.component.add("Physics", { kind = "kinematic" })
pole.component.add("BoxCollider", { half = { 0.05, 0.05, 0.05 } })
local flag = entity.spawn("flag")
flag.position = { 0, 3.7, 0 }
flag.localScale = { 1.2, 1, 1.2 }
flag.rotation = { x = -0.7071, y = 0, z = 0, w = 0.7071 } -- a cloth lies in its local XZ plane; this stands it up, local +z on top
flag.component.add("SoftBody", { shape = "cloth", resolution = 6, mass = 0.5 })
-- every particle on the top face of the unit box (local z = 0.5)
Physics.attachSoftRegion(flag, pole, { box = { min = { -0.5, -1, 0.5 }, max = { 0.5, 1, 0.5 } } })
pole.position = { 2, 4.6, 0 } -- the flag goes with it
A region names part of the soft body by where its particles stand: { box = { min, max } } is every particle between the two corners, { nearest = point } the one particle nearest the point. Coordinates are in the soft body entity's unit box (-0.5 to 0.5 on each axis, before its scale), so a region stays the same part of the body wherever the body stands and however it is scaled. A generated body's outer particles stand their contact skin inside that box (the skin is what fills it out to the box), and a box counts a particle whose skin reaches into it, so a box drawn flat on a face of the unit box, min = { -0.5, -1, -1 }, max = { -0.5, 1, 1 }, holds that face's particles; space = "world" reads them in world space instead. Physics.softRegion(region) checks one and returns the engine's form, naming the key at fault. Each particle in the region is tied to the point of the rigid body it stands at when the attachment is made, so place the two where they should join first. Keep the rigid body's colliders clear of the held region's contact skin: where they overlap, the hold and the contact push against each other, and the hold's load reads that fight rather than the weight it carries (or Physics.ignoreCollision(soft, rigid) keeps the two from colliding).
Attachments live on the soft body's SoftBody component (attachments, a list of { target, region }), so they are saved with the scene, reach every peer, and can be authored there directly, a scene's build.luau included, where an entry's target names the rigid body the build placed and keeps naming it across rebuilds; Physics.attachSoftRegion(soft, rigid, region) and the component's :attach(rigid, region) add an entry and return its index, and Physics.detachSoftRegion(soft, rigid?) / :detach(rigid?) release the regions held to one rigid body, or all of them. Changing the list re-ties only the entries that changed, without rebuilding the body; a rebuilt body (a field written) is tied again. Removing either side releases the hold: a despawned rigid body lets its region fall, and a later entity with the same id is held again.
local s = Physics.softBodyState(flag)
for _, a in s.attachments do
print(a.target, a.region, a.particles, a.attached, a.force.y) -- newtons the region pulls its body with: -4.9 for the 0.5 kg flag at rest
if a.refusal then print(a.refusal) end -- why an entry holds nothing (no rigid body yet, an empty region, ...)
end
print(s.attachedParticles)
A car whose body dents is a rigid chassis carrying the wheels (see Vehicles below) and a soft shell held to it along its floor: the car drives as a rigid body and the shell deforms on impact. A plasticYield makes the shell keep its dents after the crash (see plasticity above); without one it springs back within a second. A shell held above its chassis crumples where something its own height meets it; a post, a pole or anything narrower than the chassis meets the rigid chassis first, so build that car the way "A car that crumples against a post or a pole" below does.
local shell = entity.spawn("shell")
shell.position = { 0, 1.8, 0 } -- above the chassis, its floor clear of the chassis collider
shell.localScale = { 1.8, 0.8, 4 }
shell.component.add("SoftBody", {
shape = "box", resolution = 8, stiffness = 20000, mass = 40,
plasticYield = 0.02, -- crash dents stay
})
shell.component.get("SoftBody"):attach(car, { box = { min = { -0.5, -0.5, -0.5 }, max = { 0.5, -0.4, 0.5 } } })
-- after a crash:
print(Physics.softBodyState(shell).plastic) -- metres of dent the shell kept
shell.component.get("SoftBody"):repair() -- the body shop
Keep the shell from touching its own chassis, or the two push on each other where they touch: a shell crumpled down onto its chassis pushes the car along, and a shell resting on it stays awake solving every point of that contact. A generated body's box is the surface it collides through, its contact skin included (Physics.softBodyState(id).particleRadius reads the skin), so a shell whose box starts above the chassis' collider starts clear of it. Start the shell there, and keep each truck's shell and its own chassis from colliding while both still hit every other truck. Two ways do it. Collision bits are stored on the components, so a scene build can set them and they are saved with the scene; a pair of bits per truck covers 16 trucks:
-- truck i (1 to 16): its shell and its own chassis never touch
local chassisBit, shellBit = bit32.lshift(1, i - 1), bit32.lshift(1, 15 + i)
shell.component.get("SoftBody").collisionMemberships = shellBit
shell.component.get("SoftBody").collisionFilter = bit32.bnot(chassisBit)
Physics.setCollisionGroups(car, chassisBit, bit32.bnot(shellBit))
Physics.ignoreCollision(shell, car) keeps one named pair apart with no bits to hand out, so it covers any number of trucks. It holds for the play session it is called in, so call it where play sets the truck up, in a component's onLoad:
Physics.ignoreCollision(shell, car) -- this shell and this chassis never touch
Either way, Physics.contacts(shell) then lists no contact with its own chassis, and the car's wheels pass the shell as its chassis does, so a shell may close underneath and round the wheel arches without the wheels standing on it.
Four of these trucks, each started 14 m from the middle of a flat floor and facing it, driven head on into each other at full throttle (motorTorque = 1500 on every wheel of a 600 kg chassis with springRate = 20000, damperRate = 2000, suspensionDistance = 0.3), the drivers lifting off as they meet (the shells 64 particles each), dent every shell by 0.11 to 0.14 m. Over 185 to 240 steps from the throttle opening (they meet at about step 35, and every run went on at least 150 steps past that), counted with the loop above, at the default settings they cost 2.8 to 5.0 ms of soft body time a step on average on native and 2.4 to 8.6 ms in the browser, 5 to 34 ms at the 95th percentile, and the whole step 2.9 to 5.0 ms on average on native and 2.8 to 12.2 ms in the browser (six runs on native, four of them with the collision bits above, and five in the browser, on a busy machine): inside the budget of half the tick on average. The steps the trucks hit on cost the most, 13 to 48 ms in those runs. Two more native runs, on a machine running five times the work it has cores for, read 7.7 and 13.6 ms of soft body time a step on average, 4.2 and 3.0 ms at the median and 33 and 70 ms at the worst step: on a machine that busy the mean takes in every step the engine waited for a core, and the median is the scene's own cost. A truck parked after the crash keeps its chassis and its shell awake: about 0.4 ms of soft body time a step for a shell standing clear, and 1 to 3 ms for each shell still pressed into another, for as long as the heap stands; pull the trucks apart, or take the heap away, to get those steps back.
A car that crumples against a post or a pole
A shell held above its chassis, as in the trucks above, crumples where something its own height meets it: another truck, a wall. Driven into anything lower than the shell or narrower than the chassis (a bollard, a post, a pole), the rigid chassis meets it first, and the car bounces off it rigid: the build above, a 1000 kg chassis carrying a 60 kg shell above it, driven at 27 m/s into a post 0.25 m across and 1.2 m tall, met the post with its chassis and came back at 8.9 m/s, a third of its speed, its shell keeping a dent of 0.09 m. A rigid collider gives back its restitution of the closing speed (0.3 unless the collider states one), and a chassis that touches the obstacle at all does that whatever the shell does. Three things make a car stop on a small obstacle by crushing:
- Put the structure that crumples ahead of the rigid frame, at the height of what it should meet, so the frame stands behind it and only reaches the obstacle once the structure has crushed out of the way. Hold it to the frame by its rear face and keep the two from colliding (
Physics.ignoreCollision), and give the chassis colliderrestitution = 0. - Make it crush at a force, not at a strain. An element of a
custombody with ayieldForcecarries that force while its length flows within the substeps, however fast the hit: the force it crushes at is the yield force of the members in its section, and the energy it takes is that force times how far it crushes. A box of cells yields on its strain atplasticCreep, flowing at every substep on either solver, and takes in only part of a hit: a 300 kg soft box 1.6 x 0.8 x 1 m (stiffness2e6,plasticYield0.005,plasticCreep1000) held by its rear face ahead of a 700 kg chassis on wheels, driven at 15 m/s into a post 0.25 m across at 60 Hz, absorbed 18 kJ of the 112 kJ the car and the box struck with, kept a dent of 0.18 m and sent the car back at 5 m/s. Size the crush from the energy: a car ofmkg atvm/s stops within about½ m v² / Fmetres of crush at a crush forceF. - Keep normal use elastic. Each yielding member carries its share of the structure's weight and of the structure's mass times the hardest acceleration of normal driving, held at its rear face; keep the yield force well above that share and the structure keeps its shape on the road. Keep every member ringing below the substep rate (a
stiffnessof its own, the stability report holding), and run the world at 60 ticks a second (physics.tick_rate, the default): at 30 this box, held to a chassis on wheels, keeps yielding while the car only drives (a 0.4 m dent over 3 s of cruising at 15 m/s with nothing struck). ReadPhysics.softBodyEnergy(nose).absorbedwhile the car drives clear of everything: on a build the rate holds it stays where it is.
The crash box below is a lattice of 4 x 3 x 5 particles over 1.6 x 0.5 x 0.8 m: the members along the car and their diagonals yield at 15 kN, the members across it hold, and every member is a 1e6 N/m spring.
local function crashBox(width, height, length, mass, yieldForce, stiffness)
local nx, ny, nz = 4, 3, 5
local particles, elements = {}, {}
local function at(i, j, k) return 1 + i + nx * (j + ny * k) end
for k = 0, nz - 1 do for j = 0, ny - 1 do for i = 0, nx - 1 do
table.insert(particles, { position = { (i / (nx - 1) - 0.5) * width, (j / (ny - 1) - 0.5) * height,
(k / (nz - 1) - 0.5) * length }, mass = mass / (nx * ny * nz) })
end end end
local function rod(a, b, yields)
local member = { a = a, b = b, stiffness = stiffness }
if yields then member.yieldForce = yieldForce; member.plasticMax = 0.8 end
table.insert(elements, member)
end
for k = 0, nz - 1 do for j = 0, ny - 1 do for i = 0, nx - 1 do
local p = at(i, j, k)
if i + 1 < nx then rod(p, at(i + 1, j, k), false) end -- across the car: they hold
if j + 1 < ny then rod(p, at(i, j + 1, k), false) end
if i + 1 < nx and j + 1 < ny then rod(p, at(i + 1, j + 1, k), false); rod(at(i + 1, j, k), at(i, j + 1, k), false) end
if k + 1 < nz then -- along it: they yield
rod(p, at(i, j, k + 1), true)
if i + 1 < nx then rod(p, at(i + 1, j, k + 1), true); rod(at(i + 1, j, k), at(i, j, k + 1), true) end
if j + 1 < ny then rod(p, at(i, j + 1, k + 1), true); rod(at(i, j + 1, k), at(i, j, k + 1), true) end
end
end end end
return particles, elements
end
settings.set("physics.tick_rate", 60)
car.component.add("Physics", { kind = "dynamic", mass = 700 })
car.component.add("BoxCollider", { half = { 0.8, 0.25, 1.4 }, restitution = 0 })
-- ... the wheels, as in Vehicles below ...
local nose = entity.spawn("nose")
nose.position = { car.position.x, car.position.y, car.position.z - 1.9 } -- 0.1 m ahead of the chassis front
local particles, elements = crashBox(1.6, 0.5, 0.8, 300, 15000, 1e6)
nose.component.add("SoftBody", { shape = "custom", particles = particles, elements = elements,
particleRadius = 0.08, restitution = 0 })
nose.component.get("SoftBody"):attach(car, { box = { min = { -1, -1, 0.39 }, max = { 1, 1, 0.41 } } }) -- its rear face
Physics.ignoreCollision(nose, car)
That car (700 kg of chassis and 300 kg of crash box, the box's weight and its mass times 5 m/s² each well under a tenth of a member's yield), driven at 15 m/s into a static post 0.2 m across, never touched the post with its chassis, in six runs: it stopped 0.58 to 0.66 m past where the box's front met the post's face (a step at 60 Hz carries the car 0.25 m, so measure the crush from the gap the car closed to the post, not from the first step that reads the two touching), came back off it at 1.5 to 2.0 m/s (about a ninth of its speed), and the box kept a 0.32 to 0.37 m dent; its ledger read 86 to 97 kJ absorbed of the 112 kJ the car carried. Physics.measureSoftBody(nose, { impact = { speed = 15, radius = 0.1, carried = 700 } }) reads the same box before the car is built: a crush of 0.78 m, a rebound of 1.7 m/s, 85% of the energy absorbed and a peak deceleration of 22 g at 60 Hz, and at 30 Hz a crush of 0.74 m and 86% absorbed.
Pushing, hitting and pinning a soft body from code
The verbs that push a rigid body push a soft body too. Physics.applyForce, applyImpulse, setVelocity, addVelocity, getVelocity, isSleeping and wakeUp take the body as a whole: a force or an impulse is shared over its particles by mass, so it moves off the way a rigid body of its mass would. A force acts over the span "A force over time, and code that runs with every step" states (once per step from Physics.onBeforeStep, once per frame from anywhere else, for a steady push); an impulse is the momentum the body gains.
To deform it, aim the push at part of it:
-- a punch at a point: the particles around it take the impulse, weighted from
-- the whole at the point to nothing at `radius`, and the body dents there
Physics.applyImpulseAtPoint(jelly, { 0, -3, 0 }, hit.point, { radius = 0.3 })
-- a car shell hitting a pole: the crash impulse at the contact
local contact = Physics.contacts(shell)[1]
Physics.applyImpulseAtPoint(shell, { -80, 0, 0 }, contact.points[1].point, { radius = 0.4 })
-- a blast: every particle (and every rigid body) pushed straight away from the centre
Physics.applyRadialImpulse(balloon, blast, 10, { radius = 3 })
-- a push on a region: these particles accelerate alike, the rest follow
Physics.applyForce(cloth, { 0, 0, 6 }, { box = { min = { -0.5, -1, 0.4 }, max = { 0.5, 1, 0.5 } } })
Physics.applyImpulse(jelly, { 0, 2, 0 }, { nearest = { 0, 0.5, 0 } })
applyImpulseAtPoint and applyForceAtPoint reach twice the spacing of the body's particles when no radius is given, and always reach at least the four particles nearest the point: a body dents in patches no finer than its particles are spaced, so a smaller dent takes a higher resolution, and a radius below the spacing spreads over that patch. On a rigid body they push at that point of it, spin included, and applyRadialImpulse pushes it by the distance to its centre of mass. A soft body with a plasticYield keeps the dent a hard enough hit leaves.
A pin holds a region still: its particles become kinematic, and the rest of the body hangs from them, rests on them or is dragged by them. Give a pin a target and its particles move together so their centre stands there; set the target every frame to drag it.
local left = Physics.pinSoftRegion(cloth, { nearest = { -0.5, 0, 0.5 } }) -- returns "pin1"
local right = Physics.pinSoftRegion(cloth, { nearest = { 0.5, 0, 0.5 } }, { name = "right" })
Physics.setPinTarget(cloth, right, { 2, 3, 0 }) -- drag that corner there (nil holds it where it stands)
Physics.releasePin(cloth, right) -- or Physics.releasePin(cloth) for every pin
-- a press driven down into a block: pin its top face and move the pin
local press = Physics.pinSoftRegion(block, { box = { min = { -0.5, 0.5, -0.5 }, max = { 0.5, 0.5, 0.5 } } })
Pins live on the SoftBody component (pins, a list of { name, region, target }, target empty to hold in place), so they are saved with the scene, reach every peer, are made again on a rebuilt body, and can be authored there: { shape = "cloth", pins = { { name = "top", region = { box = { ... } } } } }. The component's :pin(region, opts), :setPinTarget(name, position) and :release(name?) are the same verbs. Physics.softBodyState(id).pins reads each pin back (particles, pinned, target, center, refusal), and pinnedParticles counts them.
Physics.softParticles(id, region?) reads the particles a region selects: their indices, world positions and velocities, their restPositions (where each stands in the body's rest shape, placed in world space by the body's frame), which are pinned, and the selection's center and meanVelocity. Read it before and after a hit to see the dent where it landed. The region is resolved at each read against where the particles stand then, a local-space region in the body's frame as it stands now, so a read after the body has moved or sagged can select other particles than the same region did earlier: compare two reads by indices, and follow what a pin holds through Physics.softBodyState(id).pins (center) or the pinned flags rather than by its region.
local top = Physics.softParticles(jelly, { box = { min = { -0.5, 0.45, -0.5 }, max = { 0.5, 0.5, 0.5 } } })
print(top.count, top.center.y, top.meanVelocity.y)
Physics.setSoftParticles(id, particles) writes them back: positions and velocities (world space) move the particles and leave the rest shape as it was, so the body springs back from the written shape; restPositions changes the rest shape itself, the permanent part of the shape, which stays once the body settles the way a dent past plasticYield stays. A read's restPositions are where each particle rests, and a crumple's elements pull the body away from them (its visible dent is deeper than its rest places say), so to keep the shape a body stands in after a crash, write its positions as restPositions. indices names the particles in the numbering softParticles reads (from 0); without it each array holds one value per particle, in order. A read is a write of the same shape, so a shape read once can be put back: a rewind or a replay, a save game holding a damaged object, a level that starts with something already bent, a network correction, a repair that pushes one dent out. The write applies at once on the peer that simulates the body: a read straight after sees it and the next step simulates from it, and a write from Physics.onBeforeStep is the state that step starts from. Positions are written first and the body's frame is fitted to them; the rest places are then measured through that frame, and each element takes the rest shape its particles' places give it, which can differ from the one a crumple's elements flowed to: a body whose flow left its elements pulling against one another (a deep crumple) keeps a dent written back and settles a little way from the written shape, into it or out of it. Rest places that state the shape the body was built in (a read taken before its first dent) put that shape back exactly, the way Physics.repairSoftBody does, so a rewind to a moment before a crash replays the crash the same way each time. A write that places every particle (a whole read written back) is the whole state the body steps on from: two rewinds to one read fall the same way, to the bit until something touches the body. A rewind starts from the read alone, while the run the read was taken from carried on with what the solver had built up over the steps before, so the original and its rewinds can part by rounding where a hit amplifies it (a box landing on an edge tips one way or the other); writing the read back the moment it is taken, from Physics.onBeforeStep, makes the original run a replay of it as well. A read's rest places say where each particle rests, while each element of a crumple keeps a flow of its own: written back over the body while it still holds the read's dent, a read leaves those elements as they are, and written over any other state it gives each element the rest its particles' places give, so a body read with a deep crumple steps on from the two a little apart (about 1.5 cm over 20 steps where a 3 m slab's crumple pulls hardest). A pinned particle stands where it is written and its pin holds it there, whatever velocity is written to it. The frame after a write draws the body where it was written, with gameplay paused or running, so a write can be pictured straight away. It raises, changing nothing, for an index past the body's particles, an array of the wrong length, a body not built yet, or a body another peer simulates.
local saved = assert(Physics.softParticles(shell)) -- the shell as it stands, dents included
-- ... it crashes, crumples, flies off ...
Physics.setSoftParticles(shell, saved) -- and it is back, moving as it moved
local bent = assert(Physics.softParticles(bar))
Physics.setSoftParticles(bar, { restPositions = bent.positions }) -- the shape it stands in stays
local pre -- a crash that replays the same way every time
Physics.onBeforeStep(function()
local now = Physics.softParticles(shell)
if pre == nil and now and now.center.y < 3 then -- half a second above the post
pre = now
Physics.setSoftParticles(shell, pre) -- the original run is a replay of `pre` too
end
end)
-- each rewind: one onBeforeStep that writes `pre` back once, then removes itself
Physics.onBeforeStep(function() -- hold one particle's velocity every step
Physics.setSoftParticles(rope, { indices = { 0 }, velocities = { { x = 0, y = 0, z = 0 } } })
end)
Tearing and cutting: pieces that fly off
A soft body tears where it is loaded past its threshold: tearStrain on the SoftBody component is a stretch (0.4 tears an element pulled to 1.4 times its rest length), tearForce a pull in newtons on an edge. A script cuts one with Physics.cutSoftBody(id, { point = p, normal = n }), every element the plane through p meets opening along it (or { a, b, c }, a world-space blade triangle that cuts only as far as it reaches), or tears it with Physics.tearSoftBody(id, region), opening every element that holds a particle of the region. Both apply straight after the next physics step, a plane measured against the body where that step leaves it, so they act in play mode and raise in edit mode, where nothing simulates. A cut or tear that opens nothing (a blade that misses the body) says so in the log, naming the entity. Under multiplayer the peer that simulates a body is the one that tears it (see "Physics under multiplayer").
Every piece a tear splits off becomes an entity of its own: a copy of the torn entity, without its children and standing at the root of the scene (free of whatever the torn entity hangs from), whose SoftBody (its piece field naming the piece) holds the piece's body. It is drawn with its share of the torn entity's model and with its material, and it keeps the velocity, the dents and the pins and attachments that fell on its side, so a car panel torn off a chassis flies on with its crumple and drops the bolts that held its other half. The torn entity keeps the largest piece. A piece can be found, read with Physics.softBodyState, pushed, pinned, cut again and despawned like any soft body. It is play state: left out of every save, and leaving play takes it away and gives the torn entity back its whole body.
-- a flag that rips when the wind pulls it past 1.4 times its size
flag.component.add("SoftBody", { shape = "cloth", resolution = 12, tearStrain = 0.4 })
-- hear every tear: the torn entity, the pieces' entities, where and why
Physics.onSoftBodyTear(function(e)
print(e.entity, e.kind, e.position, #e.pieces) -- kind: "load" | "cut" | "tear"
for _, piece in e.pieces do
Physics.applyImpulse(piece, { x = 0, y = 2, z = 0 }) -- send the panels flying
end
end)
-- slice a jelly in two along the plane x = 0
Physics.cutSoftBody(jelly, { point = vector.create(0, 0, 0), normal = vector.create(1, 0, 0) })
-- punch a hole where a ray hit a sheet
Physics.tearSoftBody(sheet, { nearest = hit.point, space = "world" })
Physics.softBodyTears() returns the same records for a caller that polls. A tear costs bounded work in the step it happens in: maxTearsPerStep (32 by default) tears the most loaded edges first and leaves the rest for the next step, while an edge loaded past twice its threshold tears at once. minPiece is the smallest piece a tear splits off, tearSmoothing averages the load over that many seconds before the test, and interiorToughness above 1 makes the inside of the body harder to tear than its surface, so tears start at an edge or at earlier damage.
Joints with a soft body at either end
A Joint (fixed, hinge, ball, prismatic, spring, rope) takes a soft body at either end or both: a punching bag hung from a chain link, a soft tail on a character, two jellies stuck together. A soft end with no region is anchored on the body as a whole (its frame); region (this end) and remoteRegion (the connected end) anchor it on a region of its particles, the anchor then measured from the centre of those particles.
-- a soft bag on a ball joint, hung by its top particle from a fixed hook
Physics.addJoint(bag, hook, { kind = "ball", region = { nearest = { 0, 0.5, 0 } } })
-- two jellies stuck face to face, coming apart above 200 N
Physics.addJoint(a, b, {
kind = "fixed", breakForce = 200,
region = { box = { min = { 0.4, -0.5, -0.5 }, max = { 0.5, 0.5, 0.5 } } },
remoteRegion = { box = { min = { -0.5, -0.5, -0.5 }, max = { -0.4, 0.5, 0.5 } } },
})
Motors, breakForce / breakTorque, Physics.jointReaction and Physics.onJointBreak work as they do between rigid bodies. A region end is a cluster of the soft body's particles standing in for the joint (Physics.softBodyState(id).clusters counts the body's frame plus one per such end); it goes with the joint, and the joint goes with either body.
Structures from particles and elements: trusses, cables, rams
When the shape is a structure rather than a lump (a bridge truss, a crane, a tower, a cable net, a soft robot, the nodes and beams of a car body), list it: shape = "custom" builds the body from the particles and elements the component lists, each element with its own law. It is one soft body, simulated with the rest of the world, so rigid bodies stand on it, push it and are pushed by it, and it costs one solver object instead of a rigid body per member.
local particles, elements = {}, {}
for i = 0, 8 do table.insert(particles, { position = { i, 0, 0 }, mass = 20 }) end -- bottom chord, metres
for i = 0, 7 do table.insert(particles, { position = { i + 0.5, 1, 0 }, mass = 20 }) end -- top chord
for i = 1, 8 do table.insert(elements, { i, i + 1, group = "deck" }) end -- the deck
for i = 1, 7 do -- the top chord
table.insert(elements, { 9 + i, 10 + i, yieldForce = 4000, plasticMax = 0.03,
breakForce = 9000, group = "chord", breakGroup = "chord" })
end
for i = 1, 8 do
table.insert(elements, { i, 9 + i, group = "web" })
table.insert(elements, { 9 + i, i + 1, group = "web" })
end
bridge.component.add("SoftBody", {
shape = "custom", particles = particles, elements = elements,
solver = "fem", -- a loaded structure holds its shape on the FEM solver
triangles = {}, -- { a, b, c }: a surface other bodies collide with
particleRadius = 0.05, -- contact thickness of the particles and elements
pins = { { name = "left", region = { nearest = { 0, 0, 0 } } },
{ name = "right", region = { nearest = { 8, 0, 0 } } } },
plane = { normal = { 0, 0, 1 }, point = bridge.position }, -- a side-on structure stays flat
})
- Particles are
{ position, mass }in the entity's local space (metres before its scale); elements, cells, triangles and pins name them by their number in the list, from 1. - An element's
kind:rod(the default) holds its length against a pull and a push;cablepulls only and goes slack when its ends close in (a rope, a suspension hanger, a net);strutpushes only;springneeds astiffness;actuatoris a rod whose length is driven totargetLengthatspeed(a hydraulic ram, a muscle). - Its law, in SI units, 0 meaning none:
stiffnessin newtons per metre (0 holds it as stiff as the solver holds anything: a spring of 1000 Hz between its two particles, which is also the stiffest a statedstiffnessis held at, itsdampingscaled with it to keep its share of critical damping) anddampingin newton-seconds per metre, which damps that spring and so needs astiffness;maxForce, the most it pushes or pulls with before it gives way (and springs back once the load drops: a ram that stalls instead of tearing the structure);yieldForce, past which it stays bent, carrying the yield force while its length flows to where the load puts it, up toplasticMaxof its length squeezed andplasticMaxStretchstretched, after which it holds again where it stands (a hit fast enough to carry it past that bound within one physics substep can leave it set a little past it; it gives way as fast as the load moves its ends: a load just past the yield force bends it slowly, a hard hit at once;plasticCreeppaces a body's strain yield,plasticYield, and not this; a load it cannot carry takes its ends to that bound, where it stops with a jolt itsbreakForcehas to carry as well as the standing load: a 20 kg weight held by two members yielding at 100 N, 147 N each once they stand at their bound, stops there, on the default solver at 60 Hz, with 1570 N in each for one substep when they are held rigid and 656 N when they have astiffnessof 1e5 N/m);breakForce(a pull or a push) andbreakStrain(a stretch), past which it breaks;group, a name regions and break reports use;breakGroup, every element of which breaks when one does;collide(default true), whether rigid and soft bodies hit it as a segment ofparticleRadius, the push landing on its two particles. cells({ a, b, c, d }tetrahedra) give the structure solid material of the body'sstiffnessandpoisson;triangles({ a, b, c }) a surface bodies collide with, a deck a wheel drives on. AModelon the entity rides the cells or the triangles.- The solver. A structure that carries a load heavy against its own particles (a truck on a bridge, a load on a crane) wants
solver = "fem": it solves every element at once each substep, so the load reaches the supports and the structure holds its shape. The defaultconstraintssolver sweeps the elements a few times a substep, which carries a load along a chain of members only slowly: the truss below, loaded with 150 kg on 1 kg nodes, sagged over 0.7 m and was still moving after four seconds on it, against 1.3 mm and asleep onfem. Light structures (a cable net, a soft robot, springs) run well on either. - Where it stands. An element with no
stiffnessof its own is held as stiff as the solver holds anything, so the smallest change of length a world position can state is a force: within 100 m of the origin that is about 150 N for an element between 1 kg particles, and a few kilometres out it is several kilonewtons, enough to read forces in coarse steps and yield a member under a fraction of its limit. Build a load-bearing structure near the origin, or give its elements astiffnessof their own: a step is that stiffness times the resolution of the position. - A plane hold (
plane = { normal, point }, world space) puts every particle of the body on a plane and keeps it there, the way a bridge seen from the side, a 2D puzzle or a side-scroller structure stays flat in a 3D world; a single-plane truss has no stiffness across its plane, so it wants one. It is for a body built flat in the plane: a solid held to one is pressed flat into it. - What it costs. The
constraintssolver's step grows with the elements: measured on one desktop core in a release build at 60 Hz, a car-sized lattice of 288 particles and 2576 rods steps in about 1.6 ms (2.8 ms on average through a crash into a post, the frames of the impact itself up to about 25 ms while the impact-adaptive substeps run), and one of 150 particles and 1199 rods in about 0.9 ms. Thefemsolver solves every element at once, and its cost climbs much faster: the same 288-particle lattice took 45 ms a step on it. So a car body, a destructible lattice or anything past a few hundred elements runs onconstraints, andfemis for a small structure under a heavy load (a bridge truss of a few dozen members). Budget a browser and a phone or tablet at two to four times those times (a step compiled to WebAssembly runs slower than native code, and a mobile core is slower than a desktop one), which makes a body of a hundred or two particles and about a thousand elements the size of one car there.
Reading a structure. Physics.softElements(id) returns every element at once as arrays: force (newtons, positive pulling, negative pushing), strain, length, restLength, plastic (the permanent set, a share of its built length), load (the share of its break limit, 1 breaks it), broken, and endA / endB, where each element's two ends stand in world space (a broken one's, where its particles went). One call a frame colours a whole bridge by stress or finds the member about to go; the bridge itself is drawn as its elements without it (see "Ropes and cables"). Breaking: an element past its limit leaves the body whole, its particles staying; a part it disconnects becomes a piece of its own, as a tear's pieces do: a copy of the entity with its components, so a component driving the structure checks that its SoftBody's piece is empty before it acts. The read of the body's entity and the read of any piece's then answer the same: every element wherever the break left it, so one read still covers the whole structure. Physics.onSoftBodyTear hears each break with elements (each { index, group, breakGroup, force, load }, the element whose own load broke it first) and the physics step it broke in, so the first member to fail is the first element of the earliest record. Driving: Physics.driveSoftElements(id, { [n] = metres }, { speed = m_per_s }) moves element lengths from code; the drive holds until the element's fields are written again.
A side-on Warren truss of eight one-metre panels, one metre high (17 particles, 31 rigid members on the FEM solver, pinned at both ends of its deck and held to its plane), with a top chord that yields past 4 kN up to 3% and breaks past 9 kN, holds a load at its middle of 100 kg whole (the middle chord member carries about twice the load's weight), sags and holds with a permanent set at 300 kg, and at 700 kg breaks: one tear removes the whole chord, the most loaded middle member first. The physics suite runs it as "an authored truss holds below its yield, sags past it, and drops its chord past its break force".
Ropes and cables: tow lines, climbing ropes, cable stays
shape = "rope" builds a rope from its ends: a chain of segments elements from from to to (points in the entity's local space), length long, thickness across, weighing mass (1 kg a metre when 0). It is a soft body of particles and elements, built and stepped the way a custom body is, on the FEM solver unless it states another: it hangs, drapes over and wraps around what it touches, swings a load, takes pins and attachments at any particle, reads its tension along its length, breaks, cuts, and is drawn as a round tube of its thickness.
-- a 10 m rope from a hook, a 50 kg crate tied to its lower end
local rope = entity.spawn("rope", { position = { 0, 13, 0 } })
local crate = entity.spawn("crate", { position = { 0, 2.75, 0 } })
crate.localScale = { 0.5, 0.5, 0.5 }
crate.component.add("Physics", { kind = "dynamic", mass = 50 })
crate.component.add("BoxCollider", {})
rope.component.add("SoftBody", {
shape = "rope", from = { 0, 0, 0 }, to = { 0, -10, 0 }, segments = 20, thickness = 0.03, mass = 1,
canSleep = false, -- its tension is read at rest
pins = { { name = "hook", region = { nearest = { 0, 0, 0 } } } }, -- held in the world
attachments = { { target = crate.id, region = { nearest = { 0, -10, 0 } } } }, -- tied to the crate
})
print(Physics.softElements(rope.id).force[1]) -- on a later frame: about 500 N, the crate and the rope
- Its shape. A rope as long as its ends are apart (
length0) is built straight between them; a longer one is built hanging between them in the curve a hanging rope takes (a catenary, the entity's local -y down), so a rope pinned at both ends sags from its first frame. Element k joins particles k and k + 1 counted fromfrom, soPhysics.softElements(id).force[1]is the pull at thefromend.particlesandelementsstay empty: the rope lists its own, and a write of any rope field builds them again. - Its segments hold their length both ways, the way a chain's links do: the rope bends and folds at its particles, carries a pull along its length, and a segment pushed end on pushes back (a negative force) until the rope buckles.
stretchStiffnessis the pull that would stretch it to twice its length (its axial stiffness E A, the same for any number of segments): the default 1e6 N is a centimetre-thick polyester rope, stretching 0.05% under 500 N; a nylon rope is about 1e5 N, a steel cable 1e7 N. A segment is held no stiffer than the solver holds an element of no stiffness of its own (a 1000 Hz spring between its two particles), so light, short segments hold less than they ask for: a 10 m rope of 1 kg in 20 segments holds about 5e5 N, stretching 0.1% under 500 N, and fewer, heavier segments hold more. 0 takes that limit.bendStiffness(E I, newton square metres) adds hidden springs from each particle to the one after next, so a hose or a steel cable springs back toward straight where a rope hangs limp.dampingdamps the segments' stretch.breakForcesnaps a segment past that pull, and the rope comes apart into pieces, each an entity of its own (Physics.onSoftBodyTearhears it);Physics.cutSoftBodycuts it. - Holding it.
pinshold particles in the world (a hook, a post, an anchor a script drives withsetPinTarget),attachmentstie them to rigid bodies (a crate, a car's tow hitch, a grapple's hook), and aJointtakes a region of it at either end.{ nearest = point }names one particle;fromandtoare the ends. - Its tension is
Physics.softElements(id).force, one value per segment in newtons, positive pulling, read off each segment's stretch: a 10 m rope of 1 kg in 20 segments hanging a 50 kg crate settles reading 500.11 N at its top segment against the 500.06 N it carries and 490.7 to 490.9 N at its bottom one against 490.75 N, at 30 and 60 ticks a second, the crate 2 cm lower than where it was tied. A rope that falls asleep keeps the pulls it read on the step it fell asleep on, which can be a few percent from where it would settle, so a rope whose tension a script reads at rest keepscanSleep = false. - What it touches. Its segments collide as capsules of its
thicknesswith rigid bodies, terrain and other soft bodies: it drapes over a bar, wraps over a peg (a crate hung over a 10 cm peg from a rope tied at the far side hangs on the peg's side, the rope never passing into the peg, though a load that heavy against the rope's segments can go on bouncing on it), and carries what lands on it (a 10 kg box dropped onto two ropes side by side rests on them, the ropes draping under it; a single rope, a line, lets a box roll off it the way a real one does). Dragged by one end down across a box's edge, a 3 cm rope of 30 segments stays outside the box at 5 m/s at 30 ticks a second and at 6 m/s at 60; dragged faster, its free end whips around the corner and cuts into it, 1.2 cm at 8 m/s and 13 cm at 10 m/s at 30 ticks a second, under 1 cm at 60, so a world whose ropes move faster than that runs at 60. - Hanging and swinging. A 12 m rope of 24 segments between two pins 10 m apart sags 2.924 m and pulls 46.0 to 46.2 N at its middle, against the 2.926 m and 46.1 N of a chain of 24 links weighted at its joints. A 50 kg crate swinging 10 degrees on a 10 m rope swings with a period of 6.38 to 6.46 s against the pendulum's 6.39 s (within 1.1%), at 30 and 60 ticks a second. A rope is a chain the solver answers as one body, factored again every substep, so a heavy load swinging on it turns the rope's stiffness with it: a 10 kg crate let go level on a 6 m rope of 40 segments swings to the far side and back for ten seconds, stretching it at most 2.1%, its pull at the bottom of the swing about the three times the crate's weight a pendulum's is.
- It is drawn as a round tube of its thickness with the entity's material (the
Model's, the engine's default when there is none), the tube made once and carried by the particles every frame through the skinning pass, smooth through each particle, capped at the ends.Physics.softBodyState(id).renderreadsdrawnAs = "elements"and how manyelementsit draws. Any body of particles and elements alone is drawn the same way: a truss's members, a net's cords, a bridge's cables, each element a tube of its ownthickness(0 takes twice the body'sparticleRadius), a ball where three or more meet, an element listedhidden = trueleft out (a brace or a spring that is not seen), and an element that breaks no longer drawn. - What it costs. Ten 6 m ropes of 50 segments swinging at 60 ticks a second cost the physics step 0.62 ms on a desktop (0.09 ms a rope, with the engine's physics workers); a rope at rest that falls asleep costs nothing. Budget a browser and a phone at two to four times that.
Regions with a material of their own: crumple zones, soft tips
One soft body need not be one material. regions gives parts of any soft body their own: a front that crumples while the cabin holds, a soft tip on a stiff tool, padding over a frame, a structure's weak members.
shell.component.add("SoftBody", {
shape = "box", resolution = 10, stiffness = 2e5, solver = "fem",
regions = {
{ name = "crumple", region = { box = { min = { -0.5, -0.5, 0.3 }, max = { 0.5, 0.5, 0.5 } } },
stiffness = 1e4, plasticYield = 0.01, tearStrain = 0.5 },
},
})
for _, r in Physics.softBodyState(shell).regions do
print(r.name, r.cells, r.stiffness, r.plastic) -- plastic: the largest permanent strain inside it
end
shell.component.get("SoftBody"):setRegion("crumple", { stiffness = 2e4 }) -- on the running body
- A region selects particles the way
attachmentsandpinsdo ({ box = { min, max } }or{ nearest = point }in the entity's unit box, for ameshbody in the model's own local coordinates and for acustombody in those of itsparticles,space = "world"for world coordinates, read where the body stood when it was built), measured in the shape the body was built in, and an element (a cell, an edge, a fold) takes its material when all its particles are inside, so a box reaches one cell past the boundary it draws for the cells on that boundary to take it. The elements a region selects keep its material wherever the body goes, and a write of its values (:setRegion) changes the material of those elements. On acustombody,group = "name"selects the elements of that group instead. - It states
stiffness,damping,poisson,plasticYield,plasticCreep,plasticMax,tearStrain,tearForce,tearSmoothinganddensity; a value left out is the body's own, so a region that only softens keeps the body's yield. Later regions win over earlier ones where they overlap. On acustombodystiffnessandpoissonare those of itscells: a region of links (agroup, or a body with no cells) states neither and is refused naming the field when it does, since each link takes thestiffnessof its own element. - Every value but
densityapplies to the running body in place, through the field or:setRegion(name, values);density(kilograms per cubic metre of the region's cells) weighs its particles when the body is built. Physics.softBodyState(id).regionsreads each region back with what it covers (elements,cells,particles) andplastic, the largest permanent strain of its elements, 0 where it stayed elastic: a crumple zone's damage apart from the rest of the body.
A 2 m beam (a resolution-11 box of stiffness 4e6 on the FEM solver) pinned at its middle, whose right half is a region of a twentieth of that stiffness, bends under its own weight with the soft end dropping more than five times as far as the stiff end; with a plasticYield on the soft region alone, the soft region reads a permanent strain and the stiff region reads 0. The physics suite runs both.
Movers: what moves a player's body (walking, driving, flying, your own movement code)
A body that holds no rigid body of its own is moved by its mover: a component on the body whose .metadata carries the bodyMover tag. The Controllers library's CharacterController is the mover a player walks with (ZeroMind search Controllers installs it), and its VehicleController is the mover of a car. A component of your own becomes a mover the moment its .metadata says so, whatever it is called and whichever world or package it comes from: a hovercraft, a jetpack, a glider, a boat, a spaceship, a swim or climb mode, a rolling ball the player steers.
{ "tags": ["bodyMover"] }
The engine and the built-in library reach the body through its mover and never by a component name, so the tag is what makes your movement code the body's movement for everything else in the world:
- Speed changes and pushes.
Physics.setVelocity,Physics.addVelocityandPhysics.getVelocityon the body reach your mover's ownsetVelocity(x, y, z),addVelocity(x, y, z)andgetVelocity()when it declares all three, so a launch pad, a jump pad, a knockback, a rope let go of or any other code that gives a player a velocity gives it to your craft.Physics.moverOf(body)answers your component. Code that changes how fast a body moves (a speed boost, a slow zone, a power-up) reads and writes the mover'smoveSpeedthroughPhysics.moverOf(body), so it reaches whichever mover the body has. - The avatar on it. An avatar's look sizes the mover's
heightandradiusand sets itsmoveSpeedandsprintMultiplier; its animator plays the grounded or airborne pose from the mover'sgrounded;Frame.standing(body)(modules.up_frame) reads the mover'sframe;avatarStandard.visualOnlyremoves the mover by its tag. - A headset. In XR, the bodies a player wears are found by the tag, the eye height is read from the mover's
height, the player's real steps are carried through the mover'sslide(dx, dz)and the walk is told apart from standing by its velocity. - Simulated input.
inputSim'sdrivewalks a body at themoveSpeed(andsprintMultiplier) its mover states. - The player setup.
scene.playerwithroles = { controller = "<your mover>" }makes your mover the one every joining player's body moves with, replacing the mover the body carried (tools.use("scene", "player", "spawns", { controller = "Hover" })).
Each member is read only where the mover declares it, so a mover states what it has and leaves out the rest: setVelocity, addVelocity and getVelocity, moveSpeed and sprintMultiplier, height and radius, grounded, frame and slide(dx, dz). A mover that drives a rigid body (a vehicle on its wheels, a craft with a dynamic Physics component) declares no velocity verbs: the verbs land on the body.
A minimal mover, as two files of a component folder (/zero/source/Hover.component/):
-- .metadata: { "tags": ["bodyMover"] }
-- init.luau
--!desc Hovers the body it is on and carries it at the velocity it holds.
public = {
moveSpeed = Field.number(12, NoSync, "Metres per second at full throttle; a speed boost raises it."),
grounded = Field.bool(false, NoSync, "Whether the body stands on ground."),
}
local velocity = { x = 0, y = 0, z = 0 }
local function asVector(x: any, y: number?, z: number?): any
if type(x) == "table" then return x end
return { x = x, y = y, z = z }
end
function public:setVelocity(x: any, y: number?, z: number?): boolean
local v = asVector(x, y, z)
velocity = { x = v.x or 0, y = v.y or 0, z = v.z or 0 }
return true
end
function public:addVelocity(x: any, y: number?, z: number?): boolean
local v = asVector(x, y, z)
velocity.x += v.x or 0
velocity.y += v.y or 0
velocity.z += v.z or 0
return true
end
function public:getVelocity(): any
return { x = velocity.x, y = velocity.y, z = velocity.z }
end
function update(dt: number)
-- steer `velocity` from the controls up to public.moveSpeed (the input guide's "Reading input"), then move
local body = public.entity
local p = body.position
body.position = { x = p.x + velocity.x * dt, y = p.y + velocity.y * dt, z = p.z + velocity.z * dt }
end
Replacing the walking, or switching between ways of moving. The player body of a clearing or player start walks with the Controllers library's CharacterController. To move it with your own code instead, put your mover on the body and take CharacterController off it, or keep both and enable one at a time: of several movers on one body, the enabled one moves it, so a jetpack mode or a vehicle you climb into sets enabled = false on the walking mover and enabled = true on its own, and back again when it ends. Each mover reads its own controls: an input map it activates, or the Controllers library's driving intent (require("@controllers::vehicleController.vehicleIntent").vehicle()) for a driving scheme.
A mover of your own moves the body through the world by casts, the way CharacterController does: pass { mover = id } to Physics.raycast and the shape casts so one-way platforms and contact filters treat them as the body's own (see "Characters and other movers" above), add the ground's surfaceVelocity to its motion, and push what it walks into through Physics.bodyOf(hit.entityId).
Vehicles: a car on wheels
The Controllers library publishes the car controller, the camera rigs and the character controller as packages a world installs as one library: world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" }) (a ZeroMind search for Controllers, a car controller or a character controller finds it). Installed, each of its assets is named @controllers:: followed by its package and name, so its car controller is @controllers::vehicleController.VehicleController and its chase camera @controllers::cameraRigs.chase; its vehicleController package's driving guide builds a buggy with a chase camera behind it. A new world made with the clearing or player start installs it.
A drivable car, kart, truck or buggy is a dynamic chassis body with a WheelCollider on each wheel entity under it. Every wheel under one body is one wheel of that body's vehicle, which rapier's ray-cast vehicle controller simulates: each wheel casts its suspension down from where it is mounted, and the controller applies the suspension, drive, brake and tyre grip to the chassis, and the opposite of each to the dynamic body the wheel stands on, so a truck parked on a car, a deck or a seesaw weighs on it and a car driving on a floating deck pushes it back; a light body such as a small crate is pushed only as far as the tyre can follow it, and pushes the chassis back no harder than that, and one the floor's friction holds passes the tyres' grip on to the floor. A chassis BoxCollider around the wheel mounts is fine; the wheels see past it. A wheel stands on a surface whose normal faces back along its suspension within its groundAngle (45 degrees by default) and reads past a steeper face, the side of a crate, a kerb's face or a wall, to the ground beyond it, so a wheel meets a crate on the road on its top and rolls over it; a wheel given a wider groundAngle climbs steeper faces (a rock crawler at 60 climbs a 50 degree face). A wheel stands where its chassis would rest: it passes every collider its chassis is kept apart from, a body Physics.ignoreCollision pairs with the chassis, a body joined to the chassis by a joint with collideConnected = false, a collider whose collision groups and the chassis' do not admit each other, and a collider whose contactTag the contact filter answers "ignore" or "sensor" with the chassis' tag, so a ghost car ignoring the player's car drives through it wheels and all, and a car's wheels pass the soft shell its chassis ignores.
local car = entity.spawn("car")
car.position = { 0, 1, 0 }
car.component.add("Physics", { kind = "dynamic", mass = 600 })
car.component.add("BoxCollider", { half = { 0.9, 0.3, 2.0 } })
for _, at in { { -0.85, -1.3 }, { 0.85, -1.3 }, { -0.85, 1.3 }, { 0.85, 1.3 } } do
local wheel = entity.spawn("wheel", { parent = car.id })
wheel.localPosition = { at[1], -0.3, at[2] } -- the suspension mount
local tyre = entity.spawn("tyre", { parent = wheel.id })
tyre.component.add("Model", { model = "cylinder" })
tyre.localRotation = { 0, 0, 0.7071068, 0.7071068 } -- the cylinder's axis along X
tyre.localScale = { 0.7, 0.25, 0.7 }
wheel.component.add("WheelCollider", {
suspensionDistance = 0.3, springRate = 20000, damperRate = 2000,
visual = tyre, -- posed at the wheel centre, steered and spun every tick
})
end
The conventions, in one place:
- The chassis' forward is its local -Z. Positive
motorTorquedrives that way;brakeTorquestops the wheel whilemotorTorqueis 0 (on a wheel that spins on its own, below, both act at once, as torques on its axle). - Positive
steerAngle(degrees) steers right. Steer the front pair (the wheels at negative local Z) and drive whichever wheels you like. - To drive it, add the Controllers library's
VehicleControllerto the chassis:car.component.add("@controllers::vehicleController.VehicleController", { motorTorque = 1500, topSpeed = 25 }), once the world has installed the library (above). It reads its package'svehicleinput map (@controllers::vehicleController.inputMaps.vehicle) (throttle W/S, steer A/D, brake Space, handbrake Ctrl, boost Shift, recover R, camera zoom on the scroll wheel, each on keyboard, gamepad and touch) and writesmotorTorque,brakeTorqueandsteerAngleon the wheels: throttle pulled back brakes and then reverses, steering narrows with speed, and the handbrake locks the rear pair. In the air and on its roof the car moves as physics moves it: it flies ballistically off a ramp and stays where a rollover leaves it until the recover control (orrecover()) rights it. Two arcade assists are fields that are 0 until set:airControl(4 for a stunt vehicle) holds the chassis level in the air with throttle lifting the nose and steer spinning it, andrecoverAfter(3 for a stunt vehicle) sets a car lying on its roof back on its wheels after that many seconds. A road or simulator car keeps the same controller:brakeBias(0.6 to 0.7 for a road car) divides the brake between the front and rear axles,antiLock = trueholds each braked wheel at the edge of its tyre's grip so the car stops straight and keeps steering,tractionControl = trueholds each driven wheel at the edge of its tyre's grip under the throttle so a full-throttle launch pulls away as fast as the tyres allow without spinning them, on any surface and through the direct drive, its engine or aShaftNetworkof the author's (driveState().tractionLimitedreads when it acts),handbrakeWheelsnames the wheels the handbrake holds,counterSteer = 1turns the front wheels toward the way the car travels as it slides (so a handbrake slide driven from the keyboard, where A and D steer full lock or none, is held on throttle and counter-steer the way a stick holds it;driveState().slideAnglereads the slide),stability(on by default) holds the front wheels back to what the rear tyres still grip with while the rear slides past its grip and the slide grows, so a car steered past its tyres' grip, braking or not, runs wide or holds its slide instead of spinning, and a slide the driver holds stays theirs (falsefor a car whose spins or handbrake turns are the game), andengineCurve({ {rpm, N·m}, ... }) drives the wheels through an engine, a clutch, an automatic gearbox (gears,finalDrive) and differentials (differential:open,limitedorlocked), aShaftNetworkit puts on the chassis, in place of the drive that fades to nothing attopSpeed;driveState()reads the gear and the rpm. It drives the wheels from the physics step, so it answers at the step rate and underPhysics.advanceas in real time. Its README lists every field with its unit. - To drive it from code (an AI driver, a replay, an autopilot, a test), set its intent instead of the wheel fields:
car.component.get("@controllers::vehicleController.VehicleController"):setIntent({ throttle = 0.8, steer = -0.3 })each tick, on the peer that owns the chassis. The drive split, the top speed, the steering lock and the assists apply as they do to the player's controls.setIntentswitchescontrolSourcefrominputtoscript; the intent fields (throttle,steer,brake,handbrake,boosting) are synced, so every peer reads the same intent. A car added withcontrolSource = "script"takes no controls, so it drives beside the player's car, andcontrolSource = "input"hands a car that holds the controls back to the player (takeControl()gives them to one that does not). A driver of your own (a component whose.metadatacarries thebodyMovertag, "Movers" above) reads the same controls through the package'svehicleIntentmodule (require("@controllers::vehicleController.vehicleIntent").vehicle():getThrottle,getSteer,getBrake,isHandbrakeHeld,isBoosting,consumeRecoverRequest). Thescenes/player-setupskill covers making the car the player's body. The wheel fields are synced fields, and each write to one is a property change the world syncs: write a field when its value changes rather than on every tick (VehicleControllerdoes), and keep read-outs of the car (a speedometer, a HUD) off synced fields: write them as named values (car.values.set("rpm", rpm), thetopics/valuesguide), which replicate nothing unless declared to, and which a gauge (values.bind), a light's material and an engine note'sAudio(pitchValue) follow with no script copying them. - The suspension ends at a bump stop. The spring rests
suspensionDistance × targetPositionbelow the mount and compresses from there by up tosuspensionDistance; a landing the springs cannot take ends on the stops, with the tyres on the ground and the chassis' own collider clear of it, rather than with the tyres sunk in. A chassis standing past its stops is pushed back out bybumpStopRecoveryof the depth each tick, at no more thanbumpStopSpeed(m/s).Physics.getWheelState(wheel).stopImpulsereads what the stop took that tick. - Cameras for a car (a
VehicleControllervehicle): chase view, driver's seat / cockpit, hood view. A camera that follows the car reads where the car is drawn, notcar.position: the Controllers library's camera rigs do, and "Where a moving body is, and where it is drawn" below covers the read. Its@controllers::cameraRigs.chasetrails behind it at itsdistanceat any speed, comes in when a wall or a pillar is between it and the car and eases back out, and orbits on the look control (right-button drag, right stick, a right-side drag on a phone), swinging back behind when it is let go.@controllers::cameraRigs.mountrides the car at a point of its own frame: a driver's seat (offset = { x = -0.35, y = 0.9, z = 0.2 }), a hood view, a bumper view, a rear view (mountYaw = 180); the look control turns it within clamps and it returns to the mount's direction, andheadMotionmoves the driver's head with the car's acceleration (a probe at the seat, as in "Acceleration and g-force" below), so the view dips under braking and sways out of a corner. Both read their controls from the package's camera-rig map, which stays live while the car's map holds the player's controls, and both readCamera.follow, so a key that switches views writes the Camera'sbehavior(camera.behavior = asset.ref("@controllers::cameraRigs.mount", "component")); a swap attaches the rig fresh with its defaults, so set its fields after the write. The camera-rig map's look is a right-button drag on a mouse; for mouse look with no button held, point the rig'sinputMapat a map of the world's own in thecameragroup that declareslookwithpointerLock = true. Physics.vehicleState(chassisId)reads the car as aPhysicsVehicleState:speed, its forward speed (m/s, negative in reverse),groundedWheels, how many wheels are on the ground,wheels, each wheel's state, anddetachedWheels, the wheels that came off it;Physics.getWheelState(wheelId)reads one wheel as aPhysicsWheelState:isGrounded,compression,angularVelocityandrotation,skid,slipRatioandslipAngle,roadSpeed,load, the impulses and forces it applied and itscenter. A field the record does not hold is reported where it is written.- Every wheel also writes its tyre on its own entity as named values each tick:
wheel.compression,wheel.angularVelocity,wheel.skid,wheel.slipRatio,wheel.slipAngle,wheel.roadSpeed,wheel.load,wheel.forwardForce,wheel.sideForceandwheel.grounded. A tyre-squeal voice on the wheel takesvolumeValue = "wheel.skid", a gauge bindsvalues.bind(wheel, "wheel.roadSpeed"), and a script readsvalues.get(wheel, "wheel.slipRatio"), with nothing reading the wheel to copy it out. - Wheels that are hit and wheels that come off. A wheel's suspension is a ray, so a post or a wall meets the chassis and passes through the tyre.
solid = truegives the wheel a volume (the wheel entity's own collider unless it is a trigger, else a cylinder of itsradiusandwidth) that walls, posts and other cars strike on its tread and faces, while what it meets low on its tread (the ground, a ramp, a kerb lower than about 0.3 of its radius) stays the suspension's to mount. AbreakLoad(N) above 0 lets the wheel come off when the force on it (reaction: suspension, tyre and whatever strikes its volume) passes it, andPhysics.detachWheel(wheel)takes it off on command: it leaves as a dynamic body of its own (mass, default 20 kg) on the wheel entity's own collider, which leaves the chassis with it (on a cylinder of itsradiusandwidthfor a wheel with no collider of its own or whose own collider is a trigger, which then leaves the chassis with it on its body), rolling and bouncing, and the car drives on the wheels it has left. The mount is a fuse: a wheel torn off passes its chassis no more than itsbreakLoad, so a car that loses a wheel to a post carries on past it. A few tens of kN keeps wheels on through kerbs and landings (a 600 kg car reads about 2 kN per wheel at rest) and loses them in a crash (a post struck at 15 m/s reads hundreds of kN).Physics.attachWheel(wheel)puts it back on its mount.Physics.vehicleState(car)lists the wheels still on underwheelsand the ones that came off underdetachedWheels, each with itsdetachReason("load"or"command") anddetachLoad. Crash damage, demolition derbies, a kart that loses a wheel over a kerb, a trailer's wheels torn off: theWheelColliderREADME has the fields.
A tyre grips sideways where it touches the ground: a standing tyre holds its contact still, and a rolling one pushes back across it in proportion to its slip angle (sideFrictionStiffness times corneringStiffness, 10 by default, per newton of load per radian), up to sidewaysFriction times the load it carries. Gravity's pull across a slope is held within the tyre's combined grip, frictionSlip. So a car turns on the radius its steering gives until the turn asks more of its tyres than that, and then slides wide on its wheels; and a truck across a slope carries more of its weight on its downhill wheels, keeps its heading as it rolls along the slope, and past its tipping angle rolls over its downhill wheels rather than sliding down on them.
Wheelspin, lock-up and drifts: wheels that spin on their own. Give a wheel an inertia (kg·m², about half its mass times its radius squared: 1.2 for a 20 kg car wheel of radius 0.35) and it spins on its own: drive and brake are torques on its axle, its spin is integrated from them and from its tyre's reaction, and its tyre pushes along the road in proportion to the slip between its tread and the road, up to forwardFriction times its load. It is solved with the chassis at the physics tick, stable at 30 Hz and 60 Hz. A drive past the tyre's grip spins the wheel faster than the road (wheelspin, a burnout, a launch on gravel or ice), up to the wheel's maxDriveSpeed (m/s at the tread, the drive's rev limit; VehicleController sets it from its topSpeed, so a car it drives spins its wheels up to topSpeed on ice or in the air and no further); a brake past it locks the wheel while the car slides on (lock up), and since a sliding tyre keeps slideGrip of its grip (default 0.75), a car stops shorter held just short of locking; a rear pair locked on the handbrake or spun up under power lets go across the road too, so the car rotates into a drift that throttle and counter-steer hold (VehicleController's counterSteer steers the front wheels along the way the car moves as it slides, the counter-steer a car driven from the keyboard holds a drift with). Each wheel reads slipRatio (signed the way the tyre pushes the car: rolling forward, 0 rolling, above 0 in wheelspin, -1 locked), slipAngle (degrees, the drift angle at the tyre), angularVelocity, roadSpeed, load, forwardForce and sideForce through Physics.getWheelState, every tick: what traction control, anti-lock brakes, a drift score, a tyre sound or an engine's rpm read (VehicleController's tractionControl and antiLock read them with the tyre's grip curve, Physics.tyreCurve). A wheel with no inertia (the default) rolls at the road speed and reads a slip ratio of 0: an arcade wheel, its drive and brake a force at the road held to its grip. The same wheel serves a kart, a motorbike, a tank's track wheels, a train's or a robot's.
Tyre (tire) grip curves and load sensitivity. A tyre's grip is a curve over its slip, stated as data on the wheel: its force rises with the slip ratio and the slip angle to its peak (forwardFriction, sidewaysFriction times its load) at the slip its stiffness reaches it (forwardFrictionStiffness, sideFrictionStiffness times corneringStiffness), the two directions sharing one ellipse of grip; on a wheel that spins on its own it falls past the peak to slideGrip of it by slideSlip times the peak slip (1 lets go at once, a peaky sim tyre; 4 falls off gently and holds a drift). A loadSensitivity above 0 (0.1 to 0.3 for a road tyre) makes the tyre grip with less per newton the more it carries, every grip and stiffness scaled by (load / referenceLoad) ^ -loadSensitivity: a car twice as heavy on the same tyres corners at 2 ^ -loadSensitivity of the lateral acceleration, and weight transfer to the outside or front wheels gains them less grip than the load they take. Presets for common tyres are content in @builtin::modules.tyres (Tyres.with("drift", { radius = 0.35, inertia = 1.2 }); road, grippy, peaky, drift, loose, ice, heavy), and Physics.tyreCurve(wheelId) (the phys.tyreCurve tool) measures the curve a wheel states: its force against slip angle and slip ratio at each load, with the peak and the slide of each sweep, so a tune is checked by numbers.
The WheelCollider component README has every field: suspension, the bump stop (bumpStopRecovery, bumpStopSpeed) and the ground a wheel stands on (groundAngle), grip (forwardFriction, sidewaysFriction, frictionSlip, sideFrictionStiffness, corneringStiffness), spin (inertia, maxDriveSpeed, forwardFrictionStiffness, slideGrip), the grip curve (slideSlip, loadSensitivity, referenceLoad), the most force the suspension carries, the wheel visual, and how the spring and damper are held stable for the chassis they carry.
A monster truck is the same car built big: a heavy chassis, big wheels and long travel, with maxSuspensionForce raised so the springs carry the landings (the README of the Controllers library's VehicleController has the whole truck). A 2000 kg chassis (box half 1.3 x 0.4 x 2.2 m) on four wheels of radius 0.8 m mounted at (±1.5, -0.2, ±1.7), with suspensionDistance = 0.8, springRate = 25000, damperRate = 5000, maxSuspensionForce = 40000 and VehicleController { motorTorque = 4000, topSpeed = 25, airControl = 4 }, driven at an 18 degree ramp 12 m long with the throttle held, leaves it at about 17 m/s, rises 4.8 m above its ride height, flies about 22 m holding its nose 16 degrees up, comes down rear wheels first onto its stops and drives on on four wheels, the same on native and in the browser. Dropped from 12 m (about 15 m/s at the ground) it lands on its stops with its tyres on the floor and its box 0.2 m clear of it, and rises back to its ride height on four wheels. A wheel meets the ground along its chassis' down axis, so a wheel touching down on a chassis pitched nose up stands its tyre's lowest point a little below the floor, 0.045 m at 19 degrees. With the default maxSuspensionForce of 6000 N the springs of this truck carry little more than its weight: under full throttle it sat back 13 degrees, and its landings end on the stops. Raise it until the four wheels together carry several times the weight.
Drivetrains, gearboxes and geared machines: shafts, gear ratios, clutches, differentials
A ShaftNetwork couples rotating parts the way a drivetrain does: an engine with a torque curve through a clutch and a gearbox to a differential and the wheels, two tracks of a tank off one engine, a motor geared onto a winch drum or a crane's slew, a windmill driving a pump, a conveyor's rollers, a propeller on a shaft, a clockwork gear train. The network is solved inside the physics step, every part and link at once and implicitly, so a locked clutch or a locked differential holds without ringing at the 30 Hz and 60 Hz ticks, and a closed loop of gears creates no energy.
A part (an entry of the parts list, with a name) is something that turns about one axis with a moment of inertia: a free part of its own (a crankshaft, a flywheel, a gearbox shaft), the spin of a WheelCollider wheel (wheel = wheelEntity; it spins on its own, with its own inertia or the part's), or the turn of a hinge Joint (joint = hingeEntity, the joint's body against its connected body about the joint's axis; give that hinge stiffness = 0, damping = 0 so no spring pulls it back to its starting angle). A part takes a constant torque, a torque source (curve, {rpm, N·m} points interpolated in straight lines and held past the ends, scaled by throttle), friction and brake (torques holding it still, up to their size) and damping (viscous drag). A curve is driven implicitly: it drives its part up to the speed where it falls to zero and no further, which is a rev limit.
A link (an entry of the links list, with a name and a kind) couples parts by their names:
shaft:aandbturn together.gear:aturnsratiotimes as fast asb, andbtakesratiotimes the torque; 0 is neutral (nothing coupled), a negative ratio turnsbthe other way (reverse). A gearbox is agearwhoseratiothe shift logic writes.clutch:aandbturn together while the torque between them stays withincapacity(N·m) timesengage(0 to 1); past it they slip, passing that torque, and lock again once their speeds meet.differential:inputturnsratio(the final drive) times as fast as the mean ofaandb, its torque split equally between them, so a wheel on ice spins while the other stands.locked = trueholds the two sides together;preload(N·m) andbias(a torque bias ratio: one side may takebiastimes the other's torque) make it limited-slip, anddampinga viscous one.spring: a torsion spring betweenaandb(stiffnessN·m per radian,damping), a flexible shaft or a drive's compliance.
-- a rear-driven car: an engine through a clutch, a gearbox and an open differential
local net = car.component.add("ShaftNetwork", {
parts = {
{ name = "engine", inertia = 0.2, friction = 15, damping = 0.02,
curve = { {1000, 180}, {4500, 260}, {6500, 210}, {7200, 0} } }, -- rpm, N·m
{ name = "gearbox", inertia = 0.02 },
{ name = "driveshaft", inertia = 0.05 },
{ name = "rearLeft", wheel = rl }, { name = "rearRight", wheel = rr },
},
links = {
{ name = "clutch", kind = "clutch", a = "engine", b = "gearbox", capacity = 450 },
{ name = "gear", kind = "gear", a = "gearbox", b = "driveshaft", ratio = 3.2 },
{ name = "diff", kind = "differential", input = "driveshaft", a = "rearLeft", b = "rearRight", ratio = 3.9 },
},
})
-- the driver, every tick: throttle, clutch pedal, shifts
net:set("engine", { throttle = 0.8 })
net:set("clutch", { engage = 1 })
net:set("gear", { ratio = 2.1 }) -- second gear; 0 for neutral, -3.4 for reverse
net:set("diff", { locked = true }) -- a diff lock
print(net:state().parts.engine.rpm) -- a tachometer, an engine sound's pitch
-- a winch: a motor geared 30:1 onto a drum turning on a hinge
drum.component.add("Joint", { kind = "hinge", connected = crane.id, axisX = 1, axisY = 0, stiffness = 0, damping = 0 })
drum.component.add("ShaftNetwork", {
parts = { { name = "motor", inertia = 0.05, torque = 40 }, { name = "drum", joint = drum } },
links = { { name = "reduction", kind = "gear", a = "motor", b = "drum", ratio = 30 } },
})
-- a windmill driving a pump is the same: the rotor's hinge part geared onto
-- a pump part whose `damping` is the pump's load
Engines, gearboxes, shift logic, launch control, electric motor maps and traction control are content written over these fields (VehicleController drives a network this way: its gearbox, its clutch and its tractionControl): write the inputs at the tick rate with net:set (this engine's inputs, which cost no scene save and no replication, so a driver writes them every frame) and read the state back. A part's wheel and joint are entity references saved with the scene, so a scene rebuilt from its build code keeps them pointing at the wheels and hinges it makes again. Every part reads speed (rad/s), rpm, torque (what its source applied), brakeTorque and linkTorque; a part that names a wheel or a joint it cannot turn with reads problem saying why; every link reads torque (taken from a, or a differential's input), lockTorque, slip (rad/s) and slipping (a clutch past its capacity, an open or slipping differential), and both read the inputs in effect (throttle, brake, ratio, engage, locked), through net:state() or Physics.shaftNetworkState(entityId). The wheels one network drives stand under one body; the ShaftNetwork component README has every field. A car's network costs a physics tick about 0.03 to 0.05 ms on a desktop, about 0.07 ms in a desktop browser and about 0.01 to 0.02 ms in Chrome on a Galaxy Tab S11.
Driving and querying (in code)
Physics.applyImpulse(id, { 0, 10, 0 }) -- one-shot push
Physics.setVelocity(id, 0, 5, 0) -- direct velocity (numeric args), or setVelocity(id, {0,5,0})
Physics.setGravity({ 0, -9.81, 0 }) -- world gravity
local hit = Physics.raycast({ 0, 5, 0 }, { 0, -1, 0 }, 100) -- origin, direction, maxDist
if hit then print(hit.entityId, hit.body, hit.bodyType, hit.distance) end
local near = Physics.overlapSphere({ 0, 0, 0 }, 10) -- entity ids whose colliders overlap
A hit names the entity the collider was authored on (entityId) and the body that collider belongs to (body, with its kind in bodyType). They differ on a body assembled from parts: a collider on a child entity composes onto the nearest ancestor carrying Physics, so a ray into a car's door names the door as entityId and the car as body. A collider with no body above it (the ground, a wall) is static world geometry: its hit names the collider's own entity as body, with bodyType = "static".
Every push verb (applyForce, applyImpulse, applyTorque, applyForceAtPoint, applyImpulseAtPoint, applyRadialImpulse, setVelocity, addVelocity, setAngularVelocity) takes the body by its id or its entity proxy, or by the entity a collider of it was authored on, so a hit's entityId or body and an overlap's ids push what they name. An overlap names each body once, by the entity standing for it, however many colliders it is built from. A push on static world geometry, like a push on a static body, leaves it where it stands and reports nothing, so a blast loops over everything an overlap returns:
local hit = Physics.raycast(muzzle, aim, 100)
if hit then Physics.applyImpulseAtPoint(hit.body, { x = 0, y = 0, z = -20 }, hit.point) end
for _, id in Physics.overlapSphere(blast, 5) do -- each crate, a car by its own id, and the ground
Physics.applyRadialImpulse(id, blast, 60, { radius = 5 })
end
A body is built at the start of the frame after its entity is given a Physics component, and a write made before then is applied to the body as it is built, in the order the writes were made: a launcher can spawn a ball, add its collider and Physics, and hand it its speed in the same turn, and a component's awake() can set its entity moving on the spawn that added the body.
local ball = entity.spawn("ball", { position = { 0, 2, 0 } })
ball.component.add("SphereCollider", {})
ball.component.add("Physics", { kind = "dynamic" })
Physics.setVelocity(ball.id, 0, 4, 12) -- the body is built moving at this velocity
A write to an entity that carries no Physics component and no collider (and so will have no rigid body) does nothing, and the log says so, naming the entity; applyImpulseAtPoint, applyForceAtPoint with options and applyRadialImpulse refuse such an entity by name, naming the body above it when there is one. A write to a collider in the turn that gives its entity Physics reaches the body that component builds, whichever of the two was added first.
Many queries a frame: Physics.castMany
A script that casts many rays, shape casts or overlaps every frame (a crowd of guards checking their sight line to the player, a flock probing ahead, projectiles sub-stepping their flight, a vehicle's ring of ground probes) answers them all with Physics.castMany(queries, results). Each Physics.raycast pays a crossing into the engine and a fresh hit table; castMany pays one crossing for the whole set and writes the answers into the results array, rewriting the tables of the array handed back in, so a frame's queries make no garbage. Each answer is the one the single call of its kind gives.
-- every guard's sight line to the player, one call a frame; the tables are kept
local queries, results = {}, {}
local function updateSight(guards, player)
local target = player.position
for i, guard in guards do
local q = queries[i] or {}
queries[i] = q
local eye = guard.position
q.origin = vector.create(eye.x, eye.y + 1.6, eye.z)
q.direction = vector.create(target.x - eye.x, target.y + 1 - (eye.y + 1.6), target.z - eye.z)
q.maxDistance = 40
q.exclude = guard.id -- a guard's own collider never blocks its view
end
results = Physics.castMany(queries, results)
for i, r in results do
guards[i].seesPlayer = r.hit and r.entityId == player.id
end
end
A query is { origin, direction, maxDistance?, kind?, exclude?, mover? }: kind is "ray" (the default), "sphere" with radius, "capsule" with radius, halfHeight and an optional axis, "box" with halfExtents, or "overlapSphere" with radius (its centre at origin, no direction). A result is { hit, entityId, body, bodyType, point, normal, distance, startedInside, surface?, surfaceVelocity?, softBody? } with the vectors as vector values, { hit = false } for a miss, and { hit, entityIds } for an overlap. A third argument, { exclude?, mover? }, applies to every query naming none of its own. A query missing a field its kind needs, or carrying a value that is not a finite number, is refused naming its index and the field.
Forces a body carries: thrusters, rotors, fans, wind, hover pads
A push that stays on a body until something changes it (a rocket's thrusters, a drone's rotors, a fan, a hover pad, a jet pack, a constant wind on a sail, a magnet's pull, a conveyor that pushes) is a Force component, stated once. The step applies it on every step at any tick rate and any frame rate, evaluated from the pose the body starts that step at:
-- a 10 kg crate held up against gravity: it hovers where it stands
crate.component.add("Force", { force = { 0, 98.1, 0 }, space = "world" })
-- a rocket: two thruster entities under the hull, each pushing along its own +Y from where it stands
for _, x in { -1, 1 } do
local t = entity.spawn("thruster", { parent = hull, position = { x, -2, 0 } })
t.component.add("Force", { force = { 0, 600, 0 }, scaleValue = "throttle" })
end
hull.values.set("throttle", 0.8) -- one named value throttles every thruster under the hull
- Which body: the body of the entity carrying the
Force, or of its nearest ancestor holding one, so a body carries any number of forces through the entities under it, each acting where its entity stands on the body. One entity carries severalForcecomponents too, each further one under anameof its own (craft.component.add("Force", { name = "padBack", point = { -1, 0, -1 }, ... })). A force moves a dynamic body; a static or kinematic body carries it unmoved, and the log names thatForceonce. - Frames:
force(newtons) andtorque(newton-metres) are stated inspace,"local"(the default: the carrying entity's own frame, turning with the body) or"world"(fixed however the body turns).point(default the carrying entity's origin) is inpointSpace,"local"(moving with the body) or"world". A force acting off the centre of mass turns the body by r x F;throughCenterOfMass = truepushes without turning it. - Throttle and switch:
scalemultiplies the force and the torque, andscaleValuenames a named value (values.set) on the carrying entity or an ancestor whose number multiplies them too, read by the step as it stands.scaleis a component field, saved with the scene: the authored setting (a trim, a fixed thrust). A named value is live runtime state, never saved: the throttle a control writes while the game runs, so a scene that should start throttled up writes the value when it starts (a component'sawake). Writing any field, disabling the component (.enabled = false) or removing it takes effect from the next step. - Reading it back:
Physics.forces(id)lists every force a body carries (the entity carrying it and its instance name, the force and the torque it puts on the body in the world frame at the pose the body stands at now, its point and scale), their sums, andapplied, whether this engine's step applies them, in edit mode and paused as well as while the simulation steps. - Under multiplayer the fields sync like every component field and the peer simulating the body applies the force, so every peer sees the same motion. A named value a
Forcefollows is read on that peer, so the body's owner writes the throttle, and areplicaterate on it (values.declare, thetopics/valuesguide) lets the other peers read the same throttle.
Use Physics.onBeforeStep (below) for a force that is computed from where the body is or how fast it moves (a spring, buoyancy, a controller holding altitude); a Force for one that is stated once and changed now and then.
A force over time, and code that runs with every step
The simulation advances in fixed steps (physics.tick_rate, 60 a second unless the world sets it) while frames take whatever time they take, so a frame runs no step, one, or several. Physics.applyForce, applyForceAtPoint and applyTorque act over a span of simulated time, and where the call is made decides the span:
- From code that runs inside a step (a step hook, a contact listener,
fixedUpdate), a force acts on the next step alone. Write it once per step for a continuous force. - From anywhere else (
update, a task, a tool call), a force acts over the simulated time the next frame advances, shared across however many steps that frame runs. Write it once per frame for a continuous force.
Either way a force written continuously integrates to force times elapsed time at any frame rate and any tick rate: a body pushed up with its own weight floats, and a thruster's push gives the same speed at 30 or 240 ticks a second. A force written on one frame only delivers its strength times the time of the frame that follows it; for a one-off kick use applyImpulse, which lands in full on the next step. To see a world behave the same at a low and a high frame rate, cap the frame rate with renderer.setFrameRateCap(fps) and read what the display delivered with renderer.framePacing().deliveredFps (the rendering-settings guide).
A force that depends on where a body is or how fast it moves (a spring, buoyancy, a thruster holding altitude, a PID controller, an active ragdoll's balance; gravity toward a planet, an axis or a surface is a GravityField, which the solver applies at every substep with no code) is computed in Physics.onBeforeStep, which runs at the start of every step with the state that step starts from, and acts on that very step:
-- A thruster holding a 500 kg craft against gravity, every step.
local off = Physics.onBeforeStep(function(dt, step)
Physics.applyForce(craft, { 0, 500 * 9.81, 0 })
end)
-- Every step's result, at the physics rate: an energy log, a replay, a probe.
local trace = {}
Physics.onAfterStep(function(dt, step)
table.insert(trace, { step = step, y = entity(craft).position.y })
end)
off() -- the hook stops
A pull that drives an orbit or an oscillation. Gravity toward a planet, an axis or a surface is a GravityField (see "Gravity: planets, orbits, zones, and which way is down" above): the solver evaluates it at every substep, so orbits close with no code at all. For any other pull that depends on where a body is (a spring, a magnet of your own, an elastic tether), know that the solver divides every step into substeps (physics.solver_iterations, by default enough for 120 solves a second and at least 2: 2 at the default 60 Hz, 4 at 30 Hz) and holds a force over all of them, the way it holds the world's gravity vector. That is exact for a force that stays the same through the step (a thruster, a body's weight, a push), keeps joints and contacts stiff under it, and lets a push balance gravity exactly. A force computed once a step from where the body starts the step and held over the substeps feeds energy into an orbit or a spring, though: a body on a circular orbit gains about a fifth of its energy each turn at 30 ticks a second and an eighth at 60. Give such a pull as the momentum it makes over the step, Physics.applyImpulse(id, force * dt) from Physics.onBeforeStep, and the same orbit keeps its energy within half a percent at 30 and a tenth of a percent at 60:
-- A bead held to a point by a spring of stiffness k (its own gravityScale 0).
local k, mass = 40, 1
Physics.onBeforeStep(function(dt)
local p = entity(bead).position
Physics.applyImpulse(bead, { -k * p.x * dt, -k * p.y * dt, -k * p.z * dt })
end)
A push that has to balance gravity stays applyForce, which the solver holds over the step the way it applies the gravity it balances.
Physics.onAfterStep runs once the step has integrated, after that step's collision events reached their listeners and before fixedUpdate, so a read there (a position, a velocity, Physics.jointReaction, a raycast) sees what that step left. A frame of three steps runs each hook three times, in order: before, the step, the contact listeners, after, fixedUpdate, then the next step. Each receives (dt, step): the step's length and its number, the step that step's contact events carry. Inside either hook entity.position and entity.rotation of a dynamic body read where the last step left it. A hook must not wait (task.wait); spawn a task from it for work that does.
What a hook costs. One engine call runs every hook of a side, so one hook looping over a hundred bodies costs about what the loop costs, not a hundred calls. Nothing runs while no hook is registered. Physics.worldState().stepHooks counts the hooks of each side.
When a hook ends. The returned function ends it. A hook registered by a component ends with the component: removing it, destroying its entity or reloading its code disconnects it, so a component registers in awake and needs no onDestroy for it. Hooks run while the gameplay clock runs (play, or edit with the clock running).
Under multiplayer each engine runs its hooks with its own steps, the way fixedUpdate runs, and the peer that simulates a body is the one whose hook moves it: the other peers hold the body where that peer's steps put it. Push the bodies this peer simulates (a body it owns answers multiplayer.isOwner(id)); a force a hook writes on a replica of a body another peer simulates changes nothing the room sees (see "Physics under multiplayer").
Water: buoyancy, currents, pools, lakes and seas
Physics.water(point) answers where the water is at a point: the height of the
surface over it (surface), how deep the point is (depth, negative above the
surface; submerged), the surface's normal, how the surface moves
(surfaceVelocity: waves and current) and how the water at the point moves
(velocity: a current, a river's flow, and the waves' motion fading with depth),
and the bottom (floor). Physics.waterMany(points) answers a hull's points in
one call. It is nil where no water is.
Every water source is a body of water Physics.defineWater defines, and the
query reads them all: a sea from the Tidewater water kit (its WaterBody, from
ZeroMind) defines its water, a Terrain its lakes, rivers
and sea, and content a pool, a tank, a flooded room, a canal with a current
(kind = "flat" within a region), a wavy pond (kind = "waves" with listed
waves) or a grid of levels of its own (kind = "grid"). A river's water runs
down the slope of its own surface; a level lake stands still. Where bodies
overlap the one of higher priority answers, and Physics.water(point, nil, name) asks one by name.
A FluidForces component floats a body on whatever this answers inside the
physics step, from its colliders, with the water's drag and the wind's (see
"Air and water on a body" below), and the Tidewater water kit's Buoyancy
component floats a rigid body on it at the waterline a density relative to
water states, through the same step, so a crate dropped into a pool floats
with no code at all; read the water yourself for anything else that depends
on it.
The answer is evaluated on the CPU, so it costs the same in a physics step as in
a script, and a moment can be named: Physics.water(point, Physics.waterTime() + 0.5) is the water half a second from now. The water clock
(Physics.waterTime), the seconds of simulation the physics steps have covered,
is the default moment, and inside a physics step it is the moment that step
reaches, so a buoyancy force from Physics.onBeforeStep reads the water of its
own step, and a frame that drops steps drops their seconds from the water too.
Between steps it is the moment the frame draws at, the share of the way between
the last two steps the frame draws an interpolated body at (Physics.drawnPose),
so a boat floating on the sea is drawn on the surface drawn with it.
In a multiplayer session the steps keep it on the session's time, wrapped at
8192 s, by gaining or losing up to a tenth of each step's seconds, so every peer
reads one moment and floats a shared boat on one sea; an engine with no session
counts from 0. It wraps at 8192 s, so a shader takes it as a float uniform and
draws the surface the steps float bodies on:
Physics.onBeforeStep(function()
local w = Physics.water(entity(buoy).position)
if w and w.submerged then
-- Archimedes for a 0.5 m cube, and a pull toward the water's motion.
local under = math.min(w.depth, 0.5)
Physics.applyForce(buoy, { 0, 1000 * 9.81 * 0.25 * under, 0 })
local v = Physics.getVelocity(buoy)
if v then
Physics.applyForce(buoy, { (w.velocity.x - v.x) * 20, 0, (w.velocity.z - v.z) * 20 })
end
end
end)
Air and water on a body: buoyancy, drag, lift, wind
A FluidForces component makes the air and the water act on a body inside
every physics step, from the body's own surface: its solid colliders for a
rigid body, its surface triangles for a soft body. The step splits each
triangle at the water's surface, read at the moment the step reaches, so a
body floats at the depth its density gives, tips by where its weight sits,
rides the waves of a sea, and is pushed by the water's flow; above the
surface the wind (Physics.defineWind) blows on it. Every face meeting the
flow takes pressure drag (drag, the coefficient of a face meeting it
head-on) and skin drag (skinDrag) along it; a spinning body takes a Magnus
force (magnus). A LiftSurface is a wing, a spoiler, a sail, a rudder or a
keel on a rigid body: lift across the flow and drag along it by its angle of
attack, with a stall, its deflection set by a script or followed from a
named value. A Water component places still water in a box (a pond, a
pool, a canal with a current) and a Wind component places a wind (a breeze
everywhere, or a fan or an updraft in a box), each saved with its scene;
Physics.defineWater and Physics.defineWind define the same from a script.
Physics.fluidForces(id) reads what the last step put on a body:
buoyancy, drag, lift, submerged, each surface's angle of attack and
stall. Physics.airDensity() and a water body's density set how hard each
pushes.
-- A crate that floats in a pool: half as dense as water, it floats half under.
-- The pool's surface is the top of its 20 x 4 x 20 m box, at y = 0.
local pool = entity.spawn("pool", { position = { 0, -2, 0 } })
pool.component.add("Water", { size = { 20, 4, 20 } })
local crate = entity.spawn("crate", { position = { 0, 2, 0 } })
crate.component.add("Physics", { kind = "dynamic", mass = 500 })
crate.component.add("BoxCollider", { half = { 0.5, 0.5, 0.5 } })
crate.component.add("FluidForces", {})
-- A hull with its engine at the stern floats stern-down: the engine, a body
-- of its own fixed inside the hull's stern, moves the pair's centre of mass,
-- and the water turns the hull until its buoyancy stands under it. (An engine
-- fixed above a narrow hull raises the centre of mass too, and can roll it
-- over, as it would a real boat.)
local hull = entity.spawn("hull", { position = { 0, 1, 6 } })
hull.component.add("Physics", { kind = "dynamic", mass = 900 })
hull.component.add("BoxCollider", { half = { 2, 0.4, 0.8 } })
hull.component.add("FluidForces", {})
local engine = entity.spawn("engine", { position = { 1.6, 1, 6 } })
engine.component.add("Physics", { kind = "dynamic", mass = 400 })
engine.component.add("BoxCollider", { half = { 0.25, 0.2, 0.25 } })
Physics.ignoreCollision(engine, hull)
Physics.addJoint(engine, hull, { kind = "fixed", remoteAnchor = { 1.6, 0, 0 } })
-- A spoiler presses a car down by the square of its speed, and loses the
-- grip past its stall: lift toward the car's local -Y.
local wing = entity.spawn("rearWing", { parent = car, position = { 0, 1.1, -2 } })
wing.component.add("LiftSurface", { area = 0.9, normal = { 0, -1, 0 }, deflection = 10 })
-- A parachute: a level canopy falling meets the flow face-on (an angle of
-- attack of 90 degrees), so it lifts nothing and drags by dragMin + dragMax.
canopy.component.add("LiftSurface", { area = 30, dragMax = 1.3 })
-- A crosswind over the whole level, gusting, and a fan's updraft in a box.
level.component.add("Wind", { velocity = { 0, 0, 12 }, gust = 4, space = "world" })
local vent = entity.spawn("vent", { position = { 0, 3, 0 } })
vent.component.add("Wind", { velocity = { 0, 8, 0 }, size = { 4, 6, 4 }, falloff = 0.5 })
-- A cloth cape or a flag streams and flutters: its triangles take the drag.
flag.component.add("FluidForces", { water = false })
A body dropped through still air reaches the speed at which its drag carries
its weight: a 1 m cube face-down with drag = 1 falls at
sqrt(2 m g / (1.225 * 1 * 1)). The forces are worked out once a step for
each body that carries them, at the tick rate the world runs, from the hull's
triangles (simplified to at most 512, a box's 12 split to 48) with the water
read at each of their corners while the hull is within its radius of the
water, so a body far above the water pays for the air alone. The drag is met
at the velocity the step leaves the body at, along every direction and about
every axis together, so a light hull with a wide wet bottom or a sheet in a
gale settles at 30 steps a second as at 60, and a falling body keeps the
speed its drag carries its weight at. A body come to rest in the water or the
air falls asleep like any other and the solver skips it; the step still works
out the push of the air and the water on it, and wakes it when that push
changes: the water rising over it or draining away, a wind starting, a current
turning.
Physics.fluidForces(id) states the forces of the step a body last took them
in, so a script tuning a car's downforce or a boat's trim reads the numbers
the step used, with no force law of its own.
A body floats by its own mass and the volume of its hull unless density
states its density relative to the water: then that share of the hull floats
under still water whatever the mass, the way the Tidewater water kit's
Buoyancy component floats a body. hullSize and hullCenter state a box that stands
for a rigid body's surface in place of its colliders, and waterBody names
the one body of water it reads. A rigid body with no solid collider and no
hullSize has no surface for the water to act on: Physics.fluidForces
reports its hullTriangles as 0.
Wind with a shape: grids, textures, vortices, radial flows
A wind field need not be the same everywhere. Physics.defineWind takes a
kind: "steady" (the default) blows its velocity; "grid" reads a
velocity between the texels of a grid over a box, given as a list of x, y, z
numbers per texel or as the texels of a float texture ({ texels = buffer, channels = 4, x = 1, z = 3 }, each axis naming the channel it reads):
air flowing around a building, a valley channelling it, a storm front painted
over a map, wind shear stacked in layers up a cliff; "vortex" turns the
air about an axis, like a solid body inside its core of radius metres
(speed / radius rad/s) and slowing as radius / distance outside it, with an
inflow toward the axis and an updraft along it, reaching updraftRadius
metres out (the core alone by default; wider, a column that carries up what
the vortex swings around it): a tornado, a dust devil;
"radial" blows out of a point (slowing by the square of the distance) or
across a line (by the distance), or in with a negative speed: a blast, a
rotor's downwash. Every kind adds its velocity, gusts, and fades at the
edges of its region the way a steady wind does, and fields sum where they
overlap. A grid's scroll (m/s) moves its pattern through its box on the
water clock, so a gusty texture drifts across a field as the steps run, and a
drawn field drifts with the wind the bodies feel; wrap = true repeats it past
its box. With space = "entity" a field is stated in its entity's local
space and goes, turns and scales wherever the entity does: a fan on a boat, a
helicopter's downwash, a storm that drifts with the entity carrying it. The Wind component places a grid, a
vortex or a radial wind too (kind = "grid", "vortex", "radial"), saved
with its scene: a grid's velocities list, or a float texture whose red,
green and blue are the wind's x, y and z, over the component's size box,
centred on its entity.
Every reader samples the same field inside the step: the drag, lift and
Magnus force on every FluidForces body (each triangle of the hull at its
own point, so a body across a vortex's core is turned by it), a soft body's
triangles, every LiftSurface, and Physics.wind(point), which answers the
value the step applies.
-- A tornado that goes wherever the entity carrying it goes: it turns the
-- air at 30 m/s at its 6 m core, draws it in and lifts it over a column 15 m
-- from its axis.
local twister = entity.spawn("twister", { position = { 0, 0, 0 } })
Physics.defineWind("tornado", {
kind = "vortex", entity = twister, space = "entity",
radius = 6, speed = 30, inflow = 5, updraft = 15, updraftRadius = 15,
region = { min = { x = -40, y = -5, z = -40 }, max = { x = 40, y = 80, z = 40 } }, falloff = 15,
})
-- Wind channelled down a valley, from a 2 x 2 map over 100 x 100 m: each
-- texel's x, y, z, read between the texels at every height up to 40 m.
Physics.defineWind("valley", {
kind = "grid", origin = { x = -50, y = 0, z = -50 }, size = { x = 100, y = 40, z = 100 },
columns = 2, rows = 2,
velocities = { 4, 0, 0, 8, 0, 0, 2, 0, 3, 6, 0, 3 },
})
-- Gusts from a 64 x 64 float texture (red = x, blue = z), drifting across a
-- 200 m field at 6 m/s and repeating past it.
Physics.defineWind("gusts", {
kind = "grid", origin = { x = -100, y = 0, z = -100 }, size = { x = 200, y = 50, z = 200 },
columns = 64, rows = 64, velocities = { texels = gustTexels, channels = 4, x = 1, z = 3 },
scroll = { x = 6, y = 0, z = 0 }, wrap = true,
})
-- A flag reads what the bodies feel.
local w = Physics.wind(flagPole.position)
Going into and out of the water: splashes, swimming, how deep
Physics.onWater(target, fn) hears an entity go into the water and come out
of it, on the physics step it happens, from any water the water query knows:
a pool, a Water component, an ocean, a terrain's lakes and rivers, a body
Physics.defineWater defined. It works for any body (with or without
FluidForces), a character, a thrown object or a projectile, and nil hears
every dynamic and kinematic body and every character in the world. Each event
says where it crossed the surface (point, normal), which water (water),
how fast it crossed along the surface's normal (normalSpeed, against the
surface's own motion, positive going in and negative coming out), its
velocity there, the share of it under (submerged) and how deep its centre
stands (depth). The speed is the one at the moment its lowest point met the
surface, between the step before and the step after, so a ball dropped from
5 m enters at 9.9 m/s at any tick rate.
-- A splash, scaled by how hard the body hits the water.
Physics.onWater(nil, function(e)
if e.kind == "enter" and e.normalSpeed > 2 then
spawnSplash(e.point, e.normalSpeed)
end
end)
-- A swim state for the player's character.
Physics.onWater(player, function(e)
swimming = e.kind == "enter"
end)
-- How deep a wader stands, and whether a boat is going down.
local w = Physics.immersion(player)
local waistDeep = w ~= nil and (w.depth or -1) > -0.9
local b = Physics.immersion(boat)
if b and b.submerged > 0.95 then print("sinking") end
An entity goes in on the step 1% or more of it stands under, and comes out on the step no part of it does: a body floating at the surface, bobbing on waves or rocking in a wake stays in until it leaves the water whole, so it raises one entry and, when it is lifted out, one exit. A body that skips off the surface and lands again goes in twice. An entity destroyed while it is in the water, or one no listener watches any more, comes out on that step, at the surface it stood in and under the id it went in by, so every entry is followed by one exit and a count of what is in the pool stays right.
Physics.immersion(target) reads how much of an entity stands in the water:
submerged (the share of it under, 0 to 1), submergedVolume, volume,
wetArea, depth (its centre's depth under the surface, negative above it),
deepest (its lowest point's), water, surfacePoint and inWater. An
entity Physics.onWater watches reads what the last step measured; any other
is measured when you ask. The share is the one FluidForces floats a body by,
so a box half as dense as water floats reading 0.5.
An entity is measured by the first of: the volume Physics.setWaterVolume
states for it in its own frame (a capsule, a sphere or a box; a
CharacterController states its capsule, so a character walking into a lake
goes in, and a trigger hears it by the same capsule), its rigid body (the box its FluidForces states, else its solid
colliders), its own collider, or its origin as a point. A watched entity costs
the step one read of the water at its centre while the surface is more than
twice its size away, and a read at each corner of its hull nearer than
that; an entity nobody watches costs nothing. Physics.worldState().water
reads who is watched, the volumes stated, the events waiting and what the
last step spent measuring (lastStep.watched, lastStep.near,
lastStep.ms). Each engine measures the bodies it holds, the ones other
peers simulate included, so every peer hears the same entries.
A ray answers from colliders, and what to ask when the surface has none
Every physics query — raycast, raycastAll, raycastScreen, boxCast,
sphereCast, capsuleCast, overlapSphere, castMany, hasLineOfSight — answers from
the physics world, which holds colliders. A mesh that renders and carries no
collider is not in it, so a ray fired through a ground mesh, a terrain, or
anything a generator cut reports the same nil a ray through open air does.
renderer.raycast answers the same ray against the geometry the renderer
DRAWS — the surface itself, triangle by triangle, whether or not anything gave
it a body. That is the query for the height of the ground under a camera
station, a prop, a sound source or a scatter.
local hit = renderer.raycast({ x, 100, z }, { 0, -1, 0 }, 200)
if hit then eye.position = { x, hit.point.y + 1.7, z } end
A nil from a physics ray means the ray met no COLLIDER.
Physics.colliderCount() separates that from a world holding none for it to
meet, in one read off the collider set:
local hit = Physics.raycast(eye, down, 200)
if hit == nil and Physics.colliderCount() == 0 then
hit = renderer.raycast(eye, down, 200) -- nothing here is solid; ask what is drawn
end
A body at rest sleeps to save simulation cost. applyImpulse, setVelocity, and setAngularVelocity wake it for you; call Physics.wakeUp(id) to wake one yourself, and Physics.isSleeping(id) to check.
Ground that is still being built: a player who joins before it stands waits
Ground can take frames to stand: a Terrain reads its landscape before its collider stands, a voxel volume meshes its chunks on the worker threads, a level streams its floor in. Whatever builds ground holds the place it is building until its collider stands there, and Physics.groundPending(point) names who is still building ground under a point (nil when nobody is). A player placed by a PlayerSpawn waits for it by itself: while ground is held under the spawn, the body stays at the spawn point (a dynamic body is held kinematic and its mover disabled), and it is let go once the ground under it stands, or, when nothing stands there, a few frames after the last hold ends. It waits whatever already stands lower down, since the ground on its way may lie above a floor that stands. A spawn with no floor and nothing held under it waits only the few frames a scene's own floor takes to register, then falls.
Code that builds ground of its own holds it the same way:
Physics.holdGround(self.entityId, { min = vector.create(-64, -20, -64), max = vector.create(64, 40, 64) })
-- ... build the colliders ...
Physics.releaseGround(self.entityId)
A hold belongs to its entity and ends when that entity leaves the world. Omit the box while the extent is not known yet: the hold then covers every place. A body of your own placed at a point waits the way a spawn does: while Physics.groundPending(p) answers a list, hold it there.
A trigger holds nothing up
A collider with isTrigger = true reports what overlaps it and blocks
nothing, and every physics query treats it that way: raycast, raycastAll,
raycastScreen, hasLineOfSight and the three casts pass through it, and
overlapSphere leaves it out. So a ray down through a trigger zone reports
the floor beneath it, a WheelCollider drives through one on the road, and a
CharacterController walks into a zone and through it the way it walks
through open air, and the zone hears it go in and out. Clicking a trigger in
the editor still selects it.
isTrigger makes a trigger of a collider whether it stands alone, rides a
body of its own entity, or rides an ancestor's body, and a trigger detects
dynamic and kinematic bodies alike, a fixed trigger zone included. A fixed
trigger leaves out the fixed geometry it stands in: a zone sunk into the floor
or crossed by a wall reports the bodies that move through it, not the floor
or the wall.
Physics.onTrigger(zone, fn) hears a body enter and leave it (see "Collision
events" below).
A trigger hears a character the way it hears a body. A CharacterController
holds no rigid body: it states its capsule (Physics.setWaterVolume), and an
entity with no body of its own is heard by every trigger through the volume
stated for it, standing where its transform puts it. So the default player
walking into a zone or over a pickup raises one enter and one exit, with
other the player's body, on every engine the player's body exists in, and a
listener on the player (Physics.onTrigger(player, fn)) hears the triggers it
goes through. A trigger on an entity beneath the character in the hierarchy
(a sensor it carries) rides with it and does not hear it, and a trigger
Physics.ignoreCollision keeps apart from it hears nothing of it, as for a
body. A mover of your own is heard the same way once it states its volume.
Moving a kinematic body
A kinematic body goes where you put it and carries the dynamic bodies it meets. Drive it either way: write its transform each frame, or give it a velocity. kind = "kinematicVelocity" is the body driven by velocity alone: the solver carries it along at the velocity you give it, step after step, and writes its pose back to the transform the way it does a dynamic body's, so a conveyor plate, a lift or a turntable set moving once keeps moving with no per-frame code:
paddle.position = { 0, 1, z } -- pose it per frame
Physics.setVelocity(paddle.id, 0, 0, 0.4) -- or hand it a velocity and let it run
While play is running, both are motion: the body travels from where it was to where you put it, and whatever stands in that span is pushed along at the speed the move implies. So a per-frame nudge carries a stack of crates the way a real platform would, and a single write across the level sweeps that whole distance, so position a kinematic body before starting play, or in small steps, when you want it somewhere without shoving what is in between.
Where the write runs decides which steps carry the move. A transform written by frame-time code (a component's update, a task, a tool call, an animated skeleton driving the bones of a ragdoll) states where the body stands at the simulated time that frame ended, and the steps replay those poses behind the frames by the longest frame of the last second and one step more, each step taking the body to the pose its moment calls for. So a body moved a little each frame travels at the speed it is moved at on every step, whether a frame runs one step or several and however uneven the frames are, and a sled, a pusher or a moving platform delivers the acceleration its script commands at any frame rate. A frame far longer than the ones before it (a hitch) slows the body for that frame rather than throwing it, and a body the script stops moving comes to rest exactly where it was last put. A transform written from Physics.onBeforeStep or fixedUpdate moves the body over one step alone, the step after the one the write was made in, exactly as far as that write says, so a body driven step by step keeps exactly its per-step motion.
The replay is why a body moved from frame-time code collides where it stood that long ago: at 2 m/s its collider trails the pose it is drawn at by about 9 cm with 60 Hz steps and 17 cm with 30 Hz steps at 60 frames a second, and further for a few seconds after a long frame. A body whose collisions have to follow input closely (a paddle, a flipper, a bat) is moved from Physics.onBeforeStep, where its collider trails its write by one step.
Physics.getVelocity(id) reads back the speed the body is actually travelling at, which is what neighbouring bodies feel.
A kinematic body moving fast (a flipper, a bat, a paddle, a rotor) strikes each dynamic body in its path at the moment within the step it reaches it, however far it moves in the step and whatever either body's ccd says: the struck body leaves at the speed of the kinematic surface where it was hit, with the pair's restitution and friction applied (restitution 0.5 sends it off at 1.5 times that speed), and ends the step clear of the kinematic body. A body lying against it as it starts to move, a ball resting on a flipper as it fires, is sent off the same way and ends every step in front of the face that pushes it. A contact listener on either body hears a strike as a begin on the step it lands in, carrying the speed the two closed at and the impulse of the strike. A strike that throws the struck body clear within the step ends on that same step; one that leaves it against the face (a ball the flipper carries) is the one contact until the two part, and ends then.
A velocity is a world-space vector at both ends: the body travels along the world axes the vector names — whatever its own rotation, and whatever its parent's — and getVelocity answers in the same frame, so setVelocity(id, v) followed by getVelocity(id) reads back v. To drive a body along its own facing, read that facing as a world direction first (entity(id).transform.forward) and scale it by the speed you want.
Collision events: contacts, impacts and triggers as they happen
A game reacts to things meeting: a hit lands, a ball touches the ground, a player walks into a zone. Listen for it and the physics step itself tells you, on the step it happened:
-- Every collision begin and end of one body (and a trigger's enter and exit).
local off = Physics.onContact(ball, function(e)
print(e.kind, e.other, e.closingSpeed) -- "begin" / "end" / "enter" / "exit"
end)
-- A hit, by how hard it lands: once per impact, on the step it lands.
Physics.onImpact(box, function(e)
-- e.impulse: N s the step applied (a rigid stop of mass m from speed v is m * v)
-- e.closingSpeed: m/s the two were approaching at as they met
-- e.points[1].point: where
playImpactSound(e.points[1].point, e.impulse)
end, { minImpulse = 50 })
-- A trigger zone: a body entering and leaving it.
Physics.onTrigger(zone, function(e)
if e.kind == "enter" then print(e.other, "entered") end
end)
off() -- stop listening
The first argument names whose collisions to hear: a body (every collider it is built from, shapes on child entities included), a collider's own entity, a trigger, or a soft body. nil hears every collision in the world. An event is seen from the entity named: entity is it, other the entity it met, collider and otherCollider the entities the two colliders were authored on, and normal points from entity towards other. An entity destroyed while it touches or stands in a trigger ends the pair with an end or exit that still names it by the id it went by, with otherRemoved (or removed, for the entity listened to) true, so a set of what is inside a zone removes it the way it removes anything else that leaves.
kind | when |
|---|---|
begin | the two start touching |
persist | every step they stay in contact (ask for it with kinds) |
end | they stop touching, or one of them goes away |
impact | their normal impulse rises past minImpulse on this step (default 0: the step a pair first takes any load) |
enter / exit | one of the two is a trigger, and the other starts or stops overlapping it |
Every event carries the step it happened in (step), how fast the two were closing along the normal as that step began (closingSpeed, m/s), the normal and friction impulse the step applied across the pair (impulse, tangentImpulse, N s; impulse divided by the step's time is the mean force), the impulse of the step before (previousImpulse), the largest one-step impulse and the sum over the contact so far (peakImpulse, totalImpulse), how many steps the two have touched (steps), and up to eight of its contact points, each with its own point, normal, distance, impulse, tangentImpulse and closingSpeed. An end carries the contact's peakImpulse and totalImpulse, and the closingSpeed the two met at.
Options are { kinds = { ... }, minImpulse = n, minSpeed = n }: kinds picks the events (default begin, end, enter, exit, plus impact when minImpulse is given), and minSpeed keeps only the begin and impact events whose closingSpeed reaches it, which is fall damage or a "hard landing" check in one line.
A body resting on something presses on it with its weight every step: mass x gravity / physics.tick_rate newton-seconds, about 1.6 N s for 10 kg at the default 60 Hz. A minImpulse below that also hears the body settle, each time its rocking lifts the load off a contact and puts it back, so set it above the resting load to hear only the hits.
When a listener runs. The step records its events itself, and listeners run once per physics step, right after it and before that step's fixedUpdate. So an impact that lasts one step is heard even when a frame runs several steps (a 120 Hz step at 60 fps, or a hitch), and a listener reacts at the physics rate. A listener must not wait (task.wait); spawn a task from it for work that does.
Listening from a component. Register in awake and the listener ends with the component: removing the component or destroying its entity disconnects it, so a component needs no onDestroy for it. listenContacts (below) ends with the component the same way.
A listener names an entity by its id. It hears whichever entity carries that id on each step, so a listener registered before a mode flip or a respawn re-creates the entity under the same id goes on hearing it, and one whose entity is gone costs the step nothing until an entity carries the id again.
-- A component that takes damage from hits.
function awake()
Physics.onImpact(public.entityId, function(e)
public.health -= e.impulse * 0.01
end, { minImpulse = 20 })
end
Polling instead of a listener. Physics.listenContacts(target, opts) keeps a target's events for Physics.contactEvents(target) to read, oldest first, however many steps ran since the last read. Physics.contactPeak(target) answers the hardest hit the target took since the last call for it ({ other, impulse, closingSpeed, step, surface?, otherSurface? }, the surfaces each side is made of where it landed), counting every step, so a script that reads once a frame still sees a one-step impact at its full impulse.
Physics.listenContacts(body)
-- each frame:
local peak = Physics.contactPeak(body)
if peak and peak.impulse > 5000 then breakApart(peak) end
What it costs. The step does this work for the colliders somebody listens to and nothing else: with nobody listening it does none, and a body nobody listens to costs nothing however many contacts it holds. A thousand listened bodies resting on the floor queue no events once they rest; persist is the event that grows with contacts, one per touching pair per step, so ask for it only where it is needed. The engine's queue keeps 4096 events between deliveries and listenContacts keeps 1024 per target, the oldest let go first; Physics.contactEventsDropped() counts what was let go. Physics.worldState().contactEvents reads what is listened to, the pairs tracked, the events waiting and what recording them cost the last step.
Under multiplayer each peer's own step records its own events, so they are local, the way fixedUpdate is. The peer that simulates a body (its owner) sees its real contacts; on a replica the body moves along that peer's poses, so its contacts there are the replica's. Decide game outcomes (damage, score, a part breaking off) on the peer that simulates the body, and share the result through a synced field or a Sync component event.
Acceleration and g-force: motion probes
The acceleration a point on a body feels is what a g-force readout, an impact severity score, a hit-strength meter, controller haptics, a flight or roller-coaster sim and racing telemetry read. Place a motion probe on the body and the physics step samples it at the rate the solver steps the body, so nothing is missed between two frames:
-- An accelerometer on a car's seat: a point of the body, in metres from the
-- body's origin along its own axes.
local stop = Physics.probeMotion(car, { point = { 0, 0.6, -0.3 }, name = "seat" })
-- each frame (or in fixedUpdate): every sample since the last read
for _, s in Physics.motionSamples(car, "seat") do
if s.g > 6 then print("hard hit", s.g, "g on step", s.step) end
end
-- the hardest moment since the last read, whether or not the samples were read
local peak = Physics.motionPeak(car, "seat")
if peak and peak.g > 30 then crashDamage(peak.g) end
stop() -- remove the probe
A sample carries:
| field | what |
|---|---|
velocity | the point's velocity, m/s |
acceleration | the change of the point's velocity per second over the sample, m/s^2: free fall reads 9.81 down. A point away from the centre of mass includes the rotation terms, centripetal (w^2 r, towards the axis) and tangential |
properAcceleration | acceleration less the gravity acting on the body: what an accelerometer at the point reads and what a rider there feels. 0 in free fall, 9.81 up at rest on the ground, and the push of a crash or a turn on top |
localProperAcceleration | the same along the body's own axes (forward, up, sideways for a seat), for haptics and cockpit readouts |
g | the length of properAcceleration in standard gravities (9.80665 m/s^2): the g-force. 1 at rest, 0 in free fall |
angularVelocity, angularAcceleration | the body's, rad/s and rad/s^2 |
step, substep, substeps, time, dt | the physics step the sample was taken in, which of that step's samples it is and how many the step took, the simulated time at its end (seconds since the probe began measuring this body) and the seconds it spans |
At the rate the solver steps the body. A probe samples every solver substep: physics.solver_iterations per step (2 at the default 60 Hz), plus the extra substeps the body's island runs while a soft body in it is hit fast or loaded hard (up to physics.soft_body_max_extra_substep_rate a second, 120 by default). At the default 60 Hz x 2 that is 120 samples a second, each dt = 1/120 s. A step the solver does not move the body in, because the body is asleep or settled, takes one sample spanning the whole step (perStep = 1), and the body is sampled every substep again from the step that wakes it. { substeps = false } takes one sample per step always. Physics.motionProbe(car, "seat") states the rate (rate, samples per second, and dt), how many samples the latest step took (perStep), how many wait, how many were let go, whether the probe is bound to a body (bound, with reason when it is not), and how many bodies it has begun measuring (session).
What acts once per step is felt over the step. A wheel's suspension and grip, and an impulse a script applies (Physics.applyImpulse, Physics.applyRadialImpulse for a blast), push the body between two steps, and the solver applies a body's damping at the end of each: a probe spreads each of them evenly over the step's samples, so a car resting on its wheels reads 1 g at every substep and a damped body reads its drag steadily. A velocity a script sets (Physics.setVelocity) is where the next sample starts from, not a push it feels.
A hit is as sharp as the sample. A rigid body stopped by a rigid wall loses its speed within a substep or two, so the peak it reads is that change over that sample: a 1500 kg car stopping from 33 m/s in one 1/120 s sample reads about 400 g. Softness spreads the stop: a body hitting a soft body (or a crumple zone built from one) stops over several steps and reads a lower, longer peak. Over a whole step the mean deceleration is the contact's impulse over mass and step (Physics.onImpact gives the impulse).
On a soft body pass a region ({ region = { nearest = { 0, 0.4, 0 } } }, as Physics.softRegion takes it): the probe measures the velocity of the region's particles averaged by mass, at every solver substep the same way, and reads no angular velocity. A soft body that is hit fast or loaded hard runs extra substeps (up to physics.soft_body_max_extra_substep_rate a second) for its island, and the probe samples each of them, as it does a rigid body in that island: a soft region of a figure's head and the rigid seat it strikes are both read at the rate the hit is solved.
What it costs. Only probed bodies cost the step anything; a body with no probe pays nothing. Each probe keeps capacity samples between two reads (default 256, up to 4096), the oldest let go first and counted (dropped). Physics.worldState().motionProbes reads the probes placed and bound, the samples waiting, and what sampling cost the last step.
A probe names an entity by its id, like a contact listener: it follows the id across a mode switch or a respawn. Each new body it measures (entering play, a respawn) starts its record afresh: the samples and the peak held of the body before are let go, time counts from zero again and session rises, so one read never mixes two runs. A probe whose entity is destroyed keeps what it took until a new body carrying the id arrives. It ends when the function probeMotion returned runs, or the component that placed it is removed or its entity destroyed. Placing it again with the same name replaces its options and keeps what it recorded.
Where a moving body is, and where it is drawn
The simulation advances in fixed ticks (physics.tick_rate, 60 a second unless the world sets it), while frames are drawn at whatever rate the display runs. So a dynamic body has two poses on any frame:
- The simulated pose. It is where the last tick left the body, and it only changes when a tick runs: sampled once a frame, a body moving at 10 m/s on a 30 Hz tick advances 0, 1/3 or 2/3 of a metre from one frame to the next, in whole ticks. The simulation acts on this pose, so code that runs inside a step (
Physics.onBeforeStepandonAfterStephooks, contact and joint listeners,fixedUpdate) reads it throughentity.position,entity.rotationandentity.worldMatrix(). - The drawn pose. A body whose
Physics.interpolationis on (the default) is drawn blended between its last two ticks, as far into the gap as the frame sits, so it moves smoothly on screen. Everything parented under the body (a car's wheels and tyres, a model parented to its collider) is drawn moved with it, and a camera or a light parented under it draws and shines from where it sits on the body as drawn. A soft body's frame is drawn the same way. The world settingphysics.interpolation = falsedraws every body at its simulated pose;Physics.interpolation = falsedoes it for one body. A body a script or the editor moves (settingentity.position, a respawn) is drawn where it was put on that frame, and the next tick blends on from there. Every read made outside a step (a component'supdate, a task, a tool call,execute) reports this pose throughentity.position,entity.rotationandentity.worldMatrix(), so a marker, a label or a follower placed from them holds steady against the body on screen at any frame rate.
Physics.drawnPose(id) reads both poses for any entity, from inside a step or outside it:
local d = Physics.drawnPose(car)
print(d.position.z) -- where the frame draws it
print(d.simulatedPosition.z) -- where the last tick left it
print(d.interpolated, d.interpolatedBy, d.alpha) -- blended?, by which body, how far into the tick
The Controllers library's camera rigs (@controllers::cameraRigs.chase, mount, third_person_follow, orbital_follow, cinematic, birds_eye, isometric, side_scroller, rts, orbit, first_person) follow the drawn pose, and a camera behavior of your own reads it through Physics.drawnPose. While the gameplay clock is paused no tick runs, and a body stays drawn where it stood when the clock stopped. Physics.drawnPose(id).simulatedPosition is the pose to compare a measurement of the simulation against (a distance travelled per tick, where to aim a force from a step hook). The Physics.* reads of a body (bodyState, getVelocity, getWheelState, jointState) state the simulation, so a distance taken between one of them and entity.position outside a step differs by up to the body's travel in one tick; measure both from the simulated pose, or both from the drawn one.
Asking what the solver holds, and why something is not moving
The Physics component carries the numbers content wrote. The simulation carries the numbers it kept, and the two part company whenever a write is refused, clamped, or aimed at a body that was never built — a mass set on a static body, a collider that resolved to nothing, a body type flipped behind the component's back. Physics.observe reads the second set.
local o = Physics.observe() -- every body in the world
for _, body in o.bodies do -- an array; each entry names its own entity
print(body.entity, body.bodyType, body.sleeping, body.stillness)
end
local b = Physics.bodyState(id) -- one body
print(b.bodyType, b.mass, b.gravityScale, b.sleeping, b.inIsland)
A body state carries what the solver resolved: body type, mass and inverse mass, centre of mass, principal inertia, gravity scale, linear and angular damping, all six lock flags, CCD, each collider with its shape and collision-group masks, its sleep timers, its velocities, the force and torque queued for the next step, its joints and their motors, and its transform constraints. Physics.setMass(id, -50) followed by Physics.bodyState(id).mass is how you find out what the solver did with the number.
Why is it not moving
local why, detail = Physics.whyStill(id)
-- "resting", "held by 4 touching contact(s), the deepest against ground at 0.0012m of penetration"
whyStill answers nil when the solver IS advancing the body, and otherwise names the nearest cause from a closed set — the thing to change, rather than a consequence of it:
| reason | what it means |
|---|---|
noBody | the entity carries no rigid body; nothing was built for it |
simulationNotStepping | the engine is not running the gameplay simulation — it is paused, or the world is still bootstrapping |
disabled | the body is disabled in the solver |
static | its body type is static, which the solver never integrates |
kinematic | its body type is kinematic and nothing is driving it |
infiniteMass | its inverse mass is zero, so no force accelerates it |
translationLocked | every axis the acceleration reaching it works along is locked — all three, or just the one gravity pulls along |
gravityDisabled | world gravity times its gravity scale is zero, and nothing is pushing it |
asleep | the solver put it to sleep, and none of the three causes above is what settled it |
outsideIsland | awake, but not in the solver's active island set on the last step |
resting | the colliders it touches are holding it up |
aboutToMove | nothing holds it and a net force reaches it — the next step accelerates it |
The three configured causes — infiniteMass, translationLocked, gravityDisabled — are read ahead of asleep, because each of them is what puts a body to sleep in the first place and each stays true once it is asleep. So a body that has been sitting still for minutes still answers with the thing to change rather than with the sleep that followed from it.
Physics.stillnessReasons() returns that list in the order the engine considers it. A body reading aboutToMove on sample after sample is having its velocity or pose written from outside the solver every frame.
Contacts
for _, c in Physics.contacts(id) do
print(c.other, c.touching, c.deepestPenetration, c.totalImpulse)
end
local touching, depth = Physics.touching(crate, ground)
contacts reports every pair one body's colliders are touching, each with the entity on the other side, the normal, how deeply the two interpenetrate, the impulse the last step applied, and the individual contact points. A pair is listed only while its surfaces touch, so every entry has at least one point (two soft bodies whose closed surfaces cross before any single point comes within reach are touching through the crossed volume, which names its particles and impulse and holds no point of its own), and a pair kept apart by Physics.ignoreCollision or by collision groups is never listed. A soft body's surface stands its particle radius out from its particles, and distances and penetrations are measured to that surface. That is the read behind "is the character grounded", "did these two interpenetrate", and "how hard did that land".
Each contact also carries how fast the two surfaces were closing along the normal as the last step began (closingSpeed, m/s, the fastest of its points), the friction impulse the step applied across the surface (tangentImpulse, N s), and the step it was measured on (step); each point carries its own normal, tangentImpulse and closingSpeed. A read describes the last step only: to hear every collision, impact and trigger as it happens, whatever rate the reading script runs at, listen for it (see "Collision events" above).
Each point carries the impulse the last step applied there, and totalImpulse is their sum. The solver holds at most four points of each contact plane as constraints, so the impulse sits on those and every other point reads zero. A body touching a mesh, a heightfield or a compound across several of its triangles, cells or children reports the points of each contact plane as the solver holds them: a point two neighbouring pieces share is listed once, and every point is placed where it lies on the piece that touches.
The world, and what a step costs
local w = Physics.worldState()
print(w.bodies.awake .. "/" .. w.bodies.total, w.contacts.touchingPairs, w.joints.impulse)
local c = Physics.stepCost()
if c then print(c.stepMs, c.narrowPhaseMs, c.solverResolutionMs) end
worldState counts what the simulation holds (bodies by type, how many are asleep, colliders, soft bodies and their particles, joints, contact pairs and points, and the bodies the last step integrated), so a body that failed to build is missing here while its component still exists. Soft bodies are a kind of their own: softBodies counts them, colliders.softBody counts their surface colliders, and none of them appears among bodies. stepCost breaks the last step into its stages (the same figures worldState().step carries), and softBodyMs / softBodyShare name the part attributed to soft bodies, apportioned by the constraints their elements handed the solver against the rigid contacts and joints; softBodies lists each soft body's part of it (see "What a soft body costs" above), worldState().softBodySettings the settings the solver runs every soft body under, and worldState().solverSettings the settings it runs every step under ("Tuning the solver"). Each is that one step, not a running window, and it is nil on a frame where nothing stepped. Consecutive steps over the same resting scene vary by tens of percent, so average several samples before quoting what a step costs.
A step runs on several threads at once: the solver works through independent groups of contacts and joints side by side, the narrow phase splits its pairs between them, and the broad phase reorganises its tree on a spare one while the rest of the step goes on. stepCost().workers is how many it ran on: the engine's data-parallel pool, sized to its share of the machine's threads. A large scene (a pile of thousands of boxes, a field of debris) therefore steps faster on a machine with more cores, natively and in a browser build with threads; a browser build without threads steps on one. Rigid bodies, contacts and joints come out the same on any number of workers, so a replay or a comparison between machines is not thrown off by a different core count; soft bodies on the FEM solver are the exception (see "When two engines reach the same state" below). The vehicles' wheel step runs on the same workers: each vehicle's suspension casts, tyres, wheel spin and drivetrain are worked out side by side, one vehicle to a worker at a time, and the vehicles that stand on another dynamic body (a deck, a crate, another car) or carry another car are stepped one after another in a fixed order, so the wheel step of a street of traffic or a racing field spreads over the workers, and every car ends where it would on one. profiler.stats breaks the wheel step's row (system.schedule.logic.update_wheel_colliders) into .gather (reading each wheel's fields), .apart (the vehicles worked out side by side), .in_turn (the vehicles stepped one after another) and .write_back (each wheel's state and named values), and states the workers' time on the vehicles worked out side by side, added up over the workers, as physics.wheel_apart_work. profiler.counters counts the vehicles the last tick stepped (physics.wheel_vehicles), those worked out side by side (physics.wheel_vehicles_apart) and the workers (physics.wheel_workers), each count's last.
Bodies spawned into one another (a script that spawns a heap of shards at one point, a stack of props placed inside each other) each overlap every other one, and a heap of N of them would hold a contact pair for each of the N * (N - 1) / 2. A body takes at most 64 pairs with other moving bodies (dynamic or kinematic) into its room, the ones nearest to it, and a pair neither of its bodies takes is left out: the two pass through each other until one of them works its way out of the heap and has room for the pair, which is created then. A pair takes room from one body that took it, so the pairs of the crates on a pallet, or of the balls in a cart, take the crates' and the balls' room and leave the pallet and the cart free to meet what they run into; a kinematic platform carrying more bodies than that carries every one the same way. A pair between a dynamic body and a fixed one (the ground, a wall, a static prop) is always made and takes no room, so a body always lands on the terrain under it, however many props rest there or on the body. A pair with a kinematic body is held like a pair of two dynamic bodies because a peer holds every body another peer simulates as a kinematic replica: a heap one peer spawns where another peer spawned one meets as many replicas as bodies of its own. A body resting on, against or among others pairs only with the few it touches (26 at most for a box packed in a grid of its kind). Which pairs a heap keeps follows from its bodies and where they stand, so the same heap steps the same way whatever the world held before it. worldState().contacts.refusedPairs counts the pairs the last step left out this way and contacts.crowdedColliders the bodies that met more than they could take, and the engine log names the entities. A heap of a few thousand bodies at one point therefore costs the step in proportion to its bodies; the spawn that piled them up is the thing to fix.
Two counts read oddly until you know which pool they cover. bodies.awake and bodies.sleeping split every body between them, static ones included — the solver never sleeps a static body, so a scene that has completely settled reads awake equal to its static count rather than zero. And colliders.total counts more than bodies.total whenever the scene holds a collider with no Physics component: those are colliders.standalone, the static colliders fixed in world space.
Both answer in edit mode as well as play mode, and neither needs a screenshot, a recording, or a probe entity.
Tuning the solver
Physics.solverSettings() reads every setting the solver runs the world under, and Physics.solverSettings({ ... }) changes the fields it names. Each is a world setting, physics.<name> in .world_settings, saved with the world; a change reads back at once and the solver runs under it from the next step, with no restart. Written in play, it lands on the play shadow and goes with the play edits; write it in edit mode for the world to keep it. A field the settings do not have, or a value of the wrong type or out of range, is refused by name. Physics.worldState().solverSettings reads what the solver itself holds.
print(Physics.solverSettings().solverIterations) -- 2
Physics.solverSettings({ tickRate = 60, solverIterations = 8, pgsIterations = 4 }) -- a bridge, a crane, a long chain
Physics.solverSettings({ lengthUnit = 100 }) -- a world built in centimetres
Field (physics. setting) | Default | What it changes |
|---|---|---|
tickRate (tick_rate) | 60 | Steps a second. |
maxCatchUpSeconds (max_catch_up_seconds), above 0 to 10 | 0.25 | The most simulated time one frame catches up, at any tick rate: a frame that owes more drops the rest, which reads as slow motion. See "Keeping up with real time" above. |
maxSubsteps (max_substeps), 1 to 1000 | 1000 | The most steps one frame runs. Past its first step a frame runs another only while its steps keep pace with the time they cover and have taken at most a quarter of the frame's wall time or 1/60 s, whichever is more. See "Keeping up with real time" above. |
solverIterations (solver_iterations), 1 to 256, or "auto" | "auto": enough for 120 solves a second at the tick rate and at least 2, so 4 at 30 Hz, 3 at 45 Hz and 2 from 60 Hz up, worked out again when the tick rate changes; it reads as that count, and a count written equal to it is saved as "auto" | Substeps each step is divided into. What a stack or a jointed structure resolves follows tick rate x substeps, and what contacts, wheels and soft impacts detect follows the tick rate. Every joint and contact is solved, and every body moved, once in each: the step costs about that many times its solve. |
pgsIterations (pgs_iterations), 1 to 16 | 1 | Passes over every joint and contact within one substep. Each pass costs a solve, and no integration, so it is the cheaper of the two ways to stiffen joints. |
stabilizationIterations (stabilization_iterations), 0 to 16 | 1 | Passes after each substep's correcting one that remove the speed the correction gave. |
warmStartCoefficient (warm_start_coefficient), 0 to 1 | 1 | The share of the impulse a contact carried on the last substep that it starts the next one from. |
warmStartJoints (warm_start_joints) | false | Whether joints start each substep from the impulse they carried on the last one (scaled by warmStartCoefficient), the way contacts do. |
lengthUnit (length_unit) | 1 | World units to a metre. The tolerances below, the sleep threshold and the speed a penetration is pushed out at are per metre and scale by it. |
contactFrequency, contactDampingRatio | 30 Hz, 10 | How stiff and how damped a contact between two moving bodies is. |
staticContactFrequency, staticContactDampingRatio | 60 Hz, 10 | The same for a contact against a fixed body: twice as stiff, so a pile is held against walls and floors. |
allowedLinearError (allowed_linear_error) | 0.005 | The slop continuous collision keeps a swept body short of what it hits. |
maxCorrectiveVelocity (max_corrective_velocity) | 3 m/s | The fastest a penetration is pushed out. |
predictionDistance (prediction_distance) | 0.02 | How far apart two shapes start producing contacts. |
ccdSubsteps (ccd_substeps), 0 to 16 | 1 | The most substeps continuous collision divides a step into; 0 turns continuous collision off for the whole world. |
frictionModel (friction_model) | "simplified" | One friction constraint per contact patch plus a twist ("simplified"), or one per contact point ("coulomb"). |
frictionInBiasPass (friction_in_bias_pass) | false | Whether friction is solved in each substep's correcting pass as well as the pass after it. |
How the defaults behave, so a world can tell expected behaviour from a defect:
- Contacts are springs. A contact pushes back as a stiff, heavily damped spring (the frequencies above), and starts acting
predictionDistancebefore the shapes touch, so a body is slowed before it arrives. A penetration is pushed out at no more thanmaxCorrectiveVelocity, so a deep overlap separates over a few steps rather than in one. - No penetration deadzone. Penetration is corrected all the way to zero: a resting body sits flush on what holds it.
allowedLinearErroris the gap continuous collision keeps, not a depth a body may sink. - Friction in the second pass. Friction is solved only in the pass after the correcting one; a stack that leans and slides toward toppling stays up because friction does not react to the correcting push.
frictionInBiasPass = truesolves it in both. - Sleep, per island. A body falls asleep after 0.5 s below 0.05 m/s (times
lengthUnit), measured at its farthest point. Bodies touching or jointed to each other sleep and wake together: one crate pushed wakes the whole stack, and one body that keeps moving keeps its pile awake. - Continuous collision against static geometry. Every fast dynamic body is swept against fixed colliders, so a body fast enough to pass through a thin wall in one step stops at it. A body's own
ccdwidens the sweep to dynamic and kinematic bodies;ccdSubsteps = 0turns all of it off. - Bounces at the end of the step. Restitution is applied once after the substeps, so a bounce leaves at the coefficient asked for, contacts started early by
predictionDistanceincluded. - Joint limits take any range. An angular limit is not confined to -180..180 degrees: a range crossing the seam works, a range wider than a full turn leaves the axis free, and a joint driven deep past its limit comes back over a few steps rather than snapping.
- The scale is metres. A world built in other units sets
lengthUnitto the units in a metre. A stack of four 50-unit boxes under a gravity of -981 (a world in centimetres) jitters and never sleeps atlengthUnit = 1, and comes to rest asleep within 2 s atlengthUnit = 100.
Joints, wheels, groups
Joint motors (see "Joint limits, motors and frames" below), wheel colliders, and collision-group filtering live on Physics (Physics.setJointMotor, Physics.addWheelCollider, Physics.setCollisionGroups). The groups an entity's CollisionGroup component states reach its colliders (its body's, its standalone collider's, and the shape it composes onto an ancestor's body) as its body is built and before every step, in edit mode as well as play, a body built or rebuilt after they were set included. A shape a child entity composes onto a body takes the child's CollisionGroup when the child has one and the body entity's otherwise, so one body can carry shapes in different groups (a car whose bumper meets what its cabin passes); Physics.bodyState(body).colliders reads each collider's memberships and filter. Groups written to an entity with no collider and no body log a warning naming it. Physics.ignoreCollision(a, b) keeps one pair of entities apart, every collider of each (a soft body's surface too), from the next step until it is turned off with false; a pair either the groups or an ignore excludes does not collide. Vehicles have a section of their own above. The phys toolbox composes the common constraints (fixed, hinge, ball, prismatic, spring, rope, generic, rail) from the tool surface.
A body that runs along a track, a curve or a line (a rollercoaster car, a train, a zip-line trolley, a slider or door on a curved guide, a bead on a wire) is a joint too: kind = "rail" holds a point on it to a path of points or a spline, through bends and loops, with ends, a motor and friction ("Rails" below).
Two bodies that join on their own when matching points meet (a trailer hitch, train couplers, a docking port, a door catch, a magnet, a part snapping into a socket) take a Latch on each point instead of a joint written by script: the step joins them with the joint the Latch states, and frees them again on a release or a break ("Latches" below).
Rope and chain behavior is a joint, not a script: kind = "rope" with maxDistance gives a maximum-distance limit solved inside the physics step: slack is free, taut resists extension, and an orbiting body on a taut rope keeps its speed. A constraint solved per-frame from Luau reads state one step late and writes one step later; for a steadily rotating configuration that lag feeds energy in every solve, so a hand-rolled rope pumps an orbiting body faster and faster. maxDistance is live: lengthening it on the running joint lets the load drop, and shortening it reels the load in. A rope with no yieldForce reels any load in at the solver's correction speed (3 m/s, 0.1 m a step at 30 ticks a second), a 5 t load as fast as a 10 kg one; a rope given one winds in at its reelSpeed pulling with at most that force (below), so a load heavier than it is not reeled in at all. A rope joint has no body between its ends: a rope that hangs, drapes over things, wraps a peg and is drawn is a SoftBody with shape = "rope" ("Ropes and cables").
Joint limits, motors and frames: doors, limbs, ragdolls, sliders, cranes
A Joint (or Physics.addJoint(a, b, opts), or the phys.addJoint tool) is more than the relative motion its kind names. Every kind measures that motion in a joint frame on each body: the frame stands at the body's anchor (localAnchor on this body, remoteAnchor on the connected one) with its X axis along axis on this body and remoteAxis on the connected one (leave remoteAxis out for the same axis, so the two frames start aligned). linX / linY / linZ are the travel along the frame's axes, angX / angY / angZ the turn about them. A hinge turns about angX, a prismatic slides along linX, a ball joint swings angX (its axis) inside a cone and twists about it. Zero on every axis is where the two frames coincide. The frame's Y and Z are the body's own Y and Z carried by the shortest turn that takes the body's X onto axis: with axis = {1, 0, 0} they are the body's own, and with axis = {0, 1, 0} the frame's Y is the body's -X and its Z the body's Z, so a generic joint's linY there slides along the body's -X. An axis reads positive as this body travels along it, or turns right-handed about it, relative to the connected body: a hinge about {0, 1, 0} reads +90 once this body has turned a quarter turn about +Y, its +Z swung round onto +X.
Limits hold a joint inside a range, solved in the physics step like contacts, so they hold under any load:
- a hinge turns between
limitMinandlimitMaxdegrees, a prismatic slides between them in metres (writing either turnslimitedon;limited = falsefrees the joint again).minAngle/maxAnglename the same two fields for a hinge; - a ball joint's axis swings inside a cone of
swingLimitdegrees (half-angle) and twiststwistLimitdegrees either way; a negative value (the default) leaves that motion free; axisLimitsbounds single axes of any kind:{ angZ = {-30, 30}, linY = { min = 0, max = 0.5 } }, degrees for an angle, metres for a travel.
-- a door that opens 0 to 110 degrees
Physics.addJoint(door, frame, { kind = "hinge", axis = {0, 1, 0}, limitMin = 0, limitMax = 110 })
-- a piston with 0.5 m of travel
Physics.addJoint(rod, cylinder, { kind = "prismatic", axis = {0, 1, 0}, limitMin = 0, limitMax = 0.5 })
Motors drive the joint: motorMode = "velocity" holds motorVelocity (radians per second for an angle, metres per second for a travel) as hard as it can; motorMode = "position" pulls toward motorTarget (degrees or metres) like a damped spring with motorStiffness and motorDamping (acceleration per unit of error by default, so one setting moves light and heavy bodies alike; motorModel = "force" reads them as force per unit of error). Neither ever applies more than motorMaxForce (newtons for a travel, newton-metres for an angle; 0 leaves it uncapped): a capped motor stalls under a load heavier than its cap instead of overpowering it. The motor drives a hinge's angle, a prismatic's travel, each angle of a ball joint (velocity 0 with a cap is joint friction, position 0 a muscle that pulls the limb back to its rest pose), and every free axis of a generic joint; axisMotors drives single axes: { angX = { mode = "velocity", velocity = 2, maxForce = 50 } }. Physics.setJointMotor(id, velocity, maxForce) and joint:setMotor(velocity, maxForce) write the same fields, so a motor is component data that syncs and reads back. A fixed, spring or rope joint has no motorable axis and refuses one.
-- a crane arm turned to 90 degrees and held there, never with more than 500 N·m
Physics.addJoint(arm, base, { kind = "hinge", axis = {0, 0, 1}, motorMode = "position", motorTarget = 90, motorMaxForce = 500 })
-- later: swing it back
entity(arm).component.get("Joint").motorTarget = 0
Yield: giving way above a force and holding again below it. yieldForce (newtons) is the most force a joint holds its travel with, yieldTorque (newton-metres) its angles. While the load needs more, the joint gives way at exactly that force or torque, solved inside the physics step at every substep; once the load falls below it, the joint holds again wherever it stands. It keeps working throughout (only breakForce / breakTorque break a joint), and 0, the default, holds without bound.
- A rope pays out:
maxDistancegrows to the length it gave way to (and reads back so), and the rope holds from there once the load is light enough. A shortermaxDistancewritten on it winds the load in atreelSpeed(metres per second, 1 by default), slowing to arrive, pulling with at mostyieldForce, so a winch with a slip clutch, a tow rope or a fishing line with drag is one rope: a load lighter than the yield comes in by the whole shortening, a heavier one pays out instead and the rope holds from where it went. A body falling onto a yielding rope brakes at the yield and pays out as it does, where a rope with no yield stops it dead. - A prismatic (
yieldForce), hinge (yieldTorque), ball (yieldTorque) or generic joint (yieldForceon its free travels,yieldTorqueon its free angles) holds its axes still below the yield and slides or turns at it above: a friction slider, a breakaway barrier, a load limiter, a seat belt's webbing, a stiff hinge. The axes take one of a yield, a motor or astiffnessspring (a motor capped bymotorMaxForceis the yield that drives somewhere).
Physics.jointState(id).slipping is true while the joint gave way over the last step, and a rope's Physics.jointState(id).length is its length as it stands; Physics.jointReaction(id) reads the force it carries (a rope's tension), which stands at the yield while it slips. A 100 kg load on a rope yielding at 600 N under 10 m/s² of gravity pays out accelerating at 4 m/s² and reads 600 N; lightened to 50 kg it decelerates at 2 m/s² and holds where it stops. A negative yield, and a reelSpeed of 0 or less, is refused naming the field: Physics.addJoint raises it, and a live write keeps the value the joint holds and reports it in the Joint's errors().
-- a winch rope that holds 3000 N and reels a lighter load in a metre at 0.5 m/s
local rope = Physics.addJoint(hook, load, { kind = "rope", maxDistance = 4, yieldForce = 3000, reelSpeed = 0.5 })
rope.maxDistance = Physics.jointState(rope).length - 1
-- a crash barrier that holds a 20 kN push and slides at it above
Physics.addJoint(barrier, post, { kind = "prismatic", axis = {1, 0, 0}, yieldForce = 20000 })
Contacts between jointed bodies. Two bodies a joint holds collide with each other by default. Parts that overlap where they are joined (limbs at a shoulder, chain links, a wheel in its arch) fight their own joint unless collideConnected = false, which turns off the contacts between those two bodies alone; every other contact stays.
A jointed body built from primitives (a figure built from boxes and capsules, a chain; a rigged character or creature is a ragdoll in one call, see "Ragdolls" below) is capsules or boxes held by ball joints with a cone and a twist and hinge joints with a range, each collideConnected = false, so a limb bends the way a limb does and never folds through its neighbour:
-- an elbow: bends 0 to 140 degrees about the arm's side axis
Physics.addJoint(forearm, upperArm, { kind = "hinge", axis = {1, 0, 0}, localAnchor = {0, 0.15, 0}, remoteAnchor = {0, -0.15, 0},
limitMin = 0, limitMax = 140, collideConnected = false })
-- a shoulder: swings 70 degrees from the arm's axis, twists 30 either way
Physics.addJoint(upperArm, torso, { kind = "ball", axis = {0, 1, 0}, localAnchor = {0, 0.15, 0}, remoteAnchor = {0.25, 0.3, 0},
swingLimit = 70, twistLimit = 30, collideConnected = false })
A generic (6DOF) joint (kind = "generic") holds the axes lockedAxes names and leaves the rest free, for any joint between the named kinds: a slider that also tilts, a suspension that travels and steers, a hinge with play. With only linY free it is a slider along the frame's Y:
Physics.addJoint(seat, rail, { kind = "generic", axis = {1, 0, 0}, lockedAxes = { "linX", "linZ", "angX", "angY", "angZ" }, axisLimits = { linY = {0, 0.3} } })
Springs. A kind = "spring" joint pulls its anchors toward restLength metres apart with stiffness (newtons per metre, default 100) and damping (default 10); with no restLength it settles at the distance its anchors stood at when it was built. A hinge, ball, prismatic or generic joint carries no spring unless its author gives it one: stiffness / damping set on one with no motorMode pull each of its axes back to where its frames align (per unit of acceleration), and left out they leave it free. The fields read -1 while they take the kind's own.
-- a bungee holding two bodies 5 m apart
Physics.addJoint(a, b, { kind = "spring", restLength = 5, stiffness = 200, damping = 20 })
-- a self-closing door
Physics.addJoint(door, frame, { kind = "hinge", axis = {0, 1, 0}, stiffness = 20, damping = 4 })
Every one of these fields is live: write it on the running joint and the next step uses it, with no rebuild, a spring's restLength included.
Reading a joint. Physics.jointState(id) answers where the joint stands as of the last step: angle (hinge, degrees) or offset (prismatic, metres) with its velocity, swing and twist (ball, degrees), atLimit while a limit holds it at a bound or pushes on it, limitForce and motorForce (what the limit and the motor applied), distance between the anchors, and axes.<linX..angZ> with the same for each axis of the frame. Physics.jointReaction(id) reads the load the whole joint carries, limit and motor included, which is what a breakForce / breakTorque is measured against (see "Reading a joint's load" below); Physics.bodyState(id).joints lists each joint a body is in with its motors. A body takes several joints; see the next section.
Several joints on one body: trusses, bridges, frames, hands
A body takes any number of joints, so a structure can hold more joints than bodies: a truss or a bridge deck of beams pinned at shared nodes, a lattice, glued blocks each glued to several neighbours, a linkage with extra links, a cab on four mounts, a hand that grabs while its arm stays jointed. The first Joint on an entity has no name; each further one is added under a name of its own (component.add("Joint", { name = "right", ... })), and Physics.addJoint(a, b, opts) names it for you (joint2, joint3, ...) and returns it. Every one is its own solver joint, with its own kind, anchors, limits, motor, break thresholds, reaction, state, break record and removal.
A joint end that is no body itself joins the nearest body above it, at that entity's position and orientation: a marker parented under a beam's end carries the joint there, with its anchor and axis measured in the marker's own frame, and connected may name a marker too. So the end of a beam is a place a joint can stand, whatever else the beam carries. A joint that cannot be built says why in the Joint's errors(): an end with no body at or above it (a collider with no Physics is static geometry, so give a wall or ledge Physics { kind = "static" } to joint to it), a connected id no entity carries, or both ends on one body.
Each joint is addressed by the Joint itself, or by its entity and name: Physics.jointState(joint), Physics.jointReaction(beam, "right"), Physics.setJointMotor(arm, 2, 300, "elbow"), Physics.removeJoint(grab), and the Joint's own joint:state() / joint:reaction(). A break record names the entity whose Joint broke in entityId and the Joint's name in joint; Physics.bodyState(id).joints lists every joint a body is in, the ones it carries and the ones that connect to it, each with its entityId, joint and other.
A truss: members are bodies, and at each node every member but the first is pinned to the first by a hinge about the plane's normal, its own end on that member's end. Members that meet at a node overlap there, so build them a little short of the node and give the joints collideConnected = false:
-- members: { member = entity, a = nodeName, b = nodeName } with each member's local X running a -> b, length `len`
local first = {} -- node name -> { entity, local x of its end there }
local function pin(member, node, x)
local f = first[node]
if f == nil then first[node] = { member, x }; return end
Physics.addJoint(member, f[1], { kind = "hinge", axis = {0, 0, 1},
localAnchor = {x, 0, 0}, remoteAnchor = {f[2], 0, 0}, collideConnected = false })
end
for _, m in members do
pin(m.member, m.a, -len / 2)
pin(m.member, m.b, len / 2)
end
-- and the two end nodes to static posts the same way
A pinned truss holds its shape because it is triangulated, and how stiff it stands is the solver's: the solver settles every joint a little short of exact on each substep, so a span of many joints sags more than its joints alone would let it. A 3-bay Warren truss of 11 members and 17 joints (6 m, 5 kg members) settles about 6 cm low at 30 Hz and 4 substeps. A 9-bay Pratt truss of 37 members and 56 joints (18 m span, 2 m deep, 5 kg members, up to five members at a node) holds at 60 Hz and 4 substeps or at 30 Hz and 8, settling about 20 cm low over 10 s, while at 30 Hz and 4 substeps it creeps lower every second and has sagged about 4 m after 10 s. A 50-bay one (100 m span) of 201 members and 302 joints builds in one script turn, in about 0.25 s; at 60 Hz it costs the physics step about 0.6 ms at 4 substeps, where it sags metres, and about 1.3 ms at 12, where it settles about 75 cm low. Raise the step rate, the substeps and the passes within each substep for a long structure (Physics.solverSettings({ tickRate = 60, solverIterations = 8, pgsIterations = 4 }), "Tuning the solver"), and measure the sag with the settings it will run at.
Jointed structures: the settings for a span. How far a jointed structure sags and how long it keeps swinging depend on how far its load travels through the joints, and so on its length in members and on how heavy its load is against the members that carry it. More substeps (solverIterations) and more passes within each (pgsIterations) both carry the load further through the joints; a pass solves the joints again without moving the bodies, so it costs less than a substep. Measured on native, stepping the solver alone (the step is the mean over the run, single-threaded; a structure that fell asleep costs next to nothing once it sleeps). "Below 0.1 m/s from" is the time after which no member moved faster than that:
| Structure | Settings (Hz / substeps / passes) | Sag over the 5th second | Stretch | Below 0.1 m/s from | Step |
|---|---|---|---|---|---|
| 20 members end to end, 1 x 0.2 x 1 m, 50 kg, fixed joints between static anchors | 30 / 4 / 1 (default) | 0.64 to 2.03 m, swinging | 12 cm | never (2.2 m/s at 5 s) | 0.14 ms |
| same | 60 / 8 / 1 | 0.09 to 0.31 m, swinging | 11 mm | never | 0.12 ms |
| same | 60 / 8 / 4 | 3.9 to 6.4 cm | 0.5 mm | never (0.04 m/s at 5 s) | 0.11 ms |
| same | 60 / 16 / 4 | 1.3 cm, asleep | under 0.1 mm | 2.2 s | 0.14 ms |
| same | 60 / 16 / 8 | 0.7 cm, asleep | under 0.1 mm | 0.9 s | 0.10 ms |
| same | 60 / 32 / 4 | 0.4 cm, asleep | under 0.1 mm | 0.4 s | 0.13 ms |
| 10 members, 20 kg, a 1000 kg box fixed at midspan | 30 / 4 / 1 (default) | 0.97 to 1.97 m, bouncing | 31 cm | never | 0.02 ms |
| same | 60 / 8 / 1 | 0.07 to 0.22 m, bouncing | 6 mm | never | 0.03 ms |
| same | 60 / 8 / 4 | 2.8 to 4.3 cm | 0.3 mm | 4.8 s | 0.05 ms |
| 100 members end to end, 50 kg | 60 / 8 / 4 | 0.8 to 3.7 m, swinging | 6 cm | never (5.7 m/s) | 0.41 ms |
| same, over the 8th second | 60 / 32 / 8 | 0.03 to 1.1 m, swinging | 3 cm | never (2.4 m/s) | 2.2 ms |
| same, over the 8th second | 60 / 64 / 4 | 0.02 to 0.8 m, swinging | 1 cm | never (1.9 m/s) | 3.8 ms |
warmStartJoints changes none of these by a measurable amount.
The rule: at 60 Hz, a span of up to about 20 members, with loads up to about fifty times a member's mass, holds within a few centimetres at 8 substeps of 4 passes, and comes to rest within about 2 s, a centimetre low, at 16 substeps of 4 to 8 passes. A span of 100 members end to end keeps swinging at any of these settings: triangulate it into a truss, or support it along its length (piers, cables to towers), so no load crosses more than about 20 joints to reach a support. The settings are the world's, so every jointed structure and every contact in the world pays for them: raise them to the least that holds the structure and measure the step with Physics.stepCost(), or ask for the substeps and passes on the structure's own bodies, where only its island pays for them (the next section).
Stiffening one structure: extra substeps on its own bodies
A jointed structure settles as stiff as the substeps its island is solved with, and a bridge, a chain or a ragdoll asks for more of them than a pile of crates does. Rather than raising the world's solver for everything, ask for them on the structure: extraSolverIterations (0 to 16) adds substeps and extraPgsIterations (0 to 16) adds passes within each, on the Physics component of every member. The island a body belongs to (everything jointed to it or touching it) runs the world's substeps plus the largest extra any of its bodies asks for, so the cost lands on that island alone, and Physics.bodyState(id).solvedSubsteps reads what the last step ran for it.
for _, member in bridge do
member.component.get("Physics").extraSolverIterations = 16
member.component.get("Physics").extraPgsIterations = 16
end
Measured on native at 60 Hz with the world at its 4 substeps, members 1 x 0.2 x 1 m of 50 kg fixed-jointed end to end between two static anchors; sag is the middle member's drop over the last second of 8, "settled" the time after which no member moved faster than 0.1 m/s, and the step cost the whole step's while the structure moves, on a busy desktop (it falls asleep once settled and costs next to nothing):
| Structure | Per body | Sag | Stretch | Settled | Step |
|---|---|---|---|---|---|
| 20 members | none | 0.38 to 0.89 m, swinging | 18 to 98 mm | never (1.2 m/s after 5 s) | 0.17 ms |
| 20 members | +12 / +4 | 0.9 to 1.2 cm, asleep | 0.02 mm | 1.7 to 1.8 s | 0.36 ms |
| 20 members | +16 / +16 | 1.7 mm, asleep | 0 | 0.13 s | 0.8 ms |
| 20 members, 1000 kg at midspan | none | 0.67 to 1.9 m, swinging | 53 to 417 mm | never (1.8 m/s after 8 s) | 0.18 ms |
| 20 members, 1000 kg at midspan | +16 / +16 | 6 mm, asleep | 0.01 mm | 1.0 s | 0.84 ms |
| 100 members | +16 / +16 | 0.13 to 2.0 m, swinging | up to 96 mm | never (1.8 m/s after 5 s) | 3.2 to 3.7 ms |
At 30 Hz the same 20-member span with a 1000 kg load at +16 / +16 settles in 4.3 s at 1.9 cm. A span of a hundred members stays a cable at any per-body setting: measure a long structure before you build a level on it, and break it into shorter spans between supports. With 200 other bodies awake in the world, the solver spent 0.40 to 0.48 ms a step on the 20-member span at +12 extra substeps on its own bodies, against 0.57 to 0.60 ms with the world's substeps raised to 16 and 0.22 ms with neither: the per-body setting leaves everything else at the world's cost.
A body held under a heavy load asks for substeps of its own as well. The pull of an impulse joint on a body at an arm from its centre of mass holds the body against a tilt as a stiff spring would, and a light link of a chain holding a heavy block sits between two such springs, which a substep longer than about 2 / (their angular frequency) cannot step stably. Each step, every awake body reads that frequency from the force its impulse joints pulled with over the step before (a joint to a body with a locked axis is left out), and its island runs the world's substeps doubled until that body tilts at most 1.5 radians in a substep, up to 64. A chain of thirty 1 kg, 0.5 m links on impulse ball joints holding a 50 kg block tilts its top links at about 133 rad/s: at 30 Hz with the world at one substep its island runs 4, at 10 Hz 16, while the rest of the world keeps the substeps it is set to. solvedSubsteps reads them, extraSolverIterations does not.
A stack asks for substeps of its own too. A substep moves each body by its load before one pass over the contacts pushes it back, so a body resting at the top of a chain of d contacts sinks about d x a x h² in a substep h long, where a is its acceleration under its load (its gravity times its gravity scale, and the forces on it over its mass). Past the error contacts leave alone, a tall stack sinks and is pushed back every substep, its friction slips under the motion, and a tower of loose stones creeps apart and never sleeps. Each step, every awake body reads its depth, the fewest touching contacts between it and a static, kinematic or sleeping body, and its island runs the world's substeps doubled until that sag stays within 1.5 times allowedLinearError (7.5 mm at the default), up to 64. At the default 60 Hz x 2 a stack under 9.81 m/s² keeps the world's 2 substeps up to 11 bodies deep and runs 4 from 12; at 30 Hz x 4 it runs 8 from 12, the same substep length. A ring tower of 480 loose stones (20 courses of 24 stones of 0.70 x 0.4 x 0.5 m and 150 kg, radius 3 m) runs 4: no stone stands 5 cm off its radius after 10 s and every stone sleeps within 2 to 4 s (the time varies with where the tower stands), where at 2 substeps over 300 stones crept more than 5 cm out and none slept; a 4 t ball at 30 m/s through it knocks out the stones it meets and the tower above the hole stands and sleeps again. A raised stack costs what its substeps cost for as long as it is awake: a pile of 2,000 boxes of 0.25 m dropped as a block 20 boxes high runs 4, and a step of it takes about what it takes with the whole world at 4 substeps, 1.5 to 3.5 times its step at 2. The bodies a stack touches run its substeps while they touch it. Reading the depths costs about what the awake bodies' contacts cost, however many sleeping bodies lie beside them, and a world whose awake bodies cannot stack that deep reads no depth at all. solvedSubsteps reads them, extraSolverIterations does not.
Articulations: chains, limbs, robot arms and ragdolls that do not stretch
A joint given articulated = true is a link of an articulation: the bodies articulated joints join form a tree, solved in reduced coordinates. An impulse joint holds two bodies together by pushing on both, so a chain of them gives a little at every link and a limit holds as well as the solver's iterations let it; an articulation states each link's pose by the coordinates its joint leaves free (a hinge's angle, a slider's travel, a ball joint's rotation), so its links cannot drift apart at all and its limits and motors act on those coordinates directly. Choose it for a chain, a crane's cable of links, a robot arm, a limb or a ragdoll: anything that is a tree of bodies under load. Keep impulse joints for loops (a truss, a bridge deck pinned at both ends, a four-bar linkage), for springs, ropes and rails, for joints that break under load, and for a joint to a soft body.
-- a chain hung from a hook: each link's joint names the link above it
local above = hook
for i, link in links do
Physics.addJoint(link, above, { kind = "ball", articulated = true, swingLimit = 30, collideConnected = false,
localAnchor = {0, 0.25, 0}, remoteAnchor = {0, if i == 1 then 0 else -0.25, 0} })
above = link
end
-- an elbow on a robot arm, driven to 45 degrees
Physics.addJoint(forearm, upperArm, { kind = "hinge", axis = {0, 0, 1}, articulated = true,
limitMin = 0, limitMax = 140, motorMode = "position", motorTarget = 45, motorMaxForce = 400 })
Each articulated joint makes one of its two bodies a link hanging from the other: the body carrying the joint, unless it already hangs from a link or is not dynamic, in which case the connected body. So write each link's joint on the link, naming its parent, and the root is whatever the first link hangs from: a static body (the articulation stands where it is held, a crane on its base), or a dynamic one (it moves freely, a ragdoll's pelvis). A fixed, hinge, ball, prismatic or generic joint takes it (a generic joint leaving none, one or all three of its angles free), with every limit, motor, spring and yield it takes as an impulse joint, and every field is live as on any joint. A joint between two bodies already in one articulation would close a loop: it is not built, and the Joint's errors() names the two bodies and the articulation's root. Removing a link's joint (Physics.removeJoint, or despawning the entity) lets the link and every link below it move on as an articulation of their own, rooted at that link.
Reading one: Physics.jointState reads an articulated joint's angle, travel, swing and limits as it reads any joint's, with articulated = true; the force its limit and motor applied is not measured (limitForce / motorForce read nil), and it carries no measured load, so Physics.jointReaction refuses it and breakForce / breakTorque are refused on it. Physics.articulation(id) reads the tree a body is a link of: its links root first, each link's parents index and linkDofs, and the dofs of the whole. An impulse, a push or a velocity written to a link moves the link and the links it is joined to as one, through the articulation's coordinates. A link's pose is its articulation's to state: a position written to a link below the root is put back at the next step, so move an articulation by its root and pose its links with Physics.solveIk.
Reaching for a target: inverse kinematics. Physics.solveIk(hand, target, opts) solves the joints above a link for the link (or the point offset in its own frame) to reach target, holding each hinge's angle and each slider's travel inside its range and turning each hinge with no range at most half a turn from where it stands (the nearest pose that reaches), and answers { reached, error, joints }. By default it puts the links there; with apply = false it only answers, and each joint's angle (degrees) or offset (metres) is the motorTarget that drives the arm there under its own motors, which is how an arm reaches while it carries a load:
local plan = Physics.solveIk(gripper, cup.position, { offset = {0.1, 0, 0}, apply = false })
for _, j in plan.joints do
local joint = entity(j.entityId).component.get("Joint")
joint.motorMode = "position"
joint.motorTarget = j.angle
end
from names the link whose joint, with every joint below it, moves (a wrist alone, the arm's base held); rotation asks the link's turn as well as its position. A target out of reach answers reached = false with the arm stretched toward it.
What it holds, measured. On native, each case run twice with the same result to the figure given, every rate at 4 substeps, the impulse joints the same joints with articulated = false:
| Case | Rate | Articulated | Impulse |
|---|---|---|---|
| 10 ball links, 0.5 m and 1 kg each, a 20 kg block for the last, 30 degree cones, the block pushed sideways by 100 N·s: the most the ten joints' anchors stood apart in all over 4 s | 60 Hz / 30 Hz | 0.1 mm / 0.1 mm | 2.3 cm / 7.9 cm |
| same: the widest any cone swung | 60 Hz / 30 Hz | 30.0 / 30.0 degrees | 30.3 / 31.2 degrees |
| 30 ball links of 1 kg hanging a 50 kg block, 15 m in all: how far it stretched over 4 s | 60 Hz / 30 Hz | under 1 mm / under 1 mm | 62 cm (4.1%) / 2.5 m (16%) |
| a 1 kg, 1 m arm on a hinge limited to 90 degrees, driven into its stop at 20 rad/s by up to 60 N·m: how far past it | 60 Hz / 30 Hz | 0 / 0 degrees | 2.9 / 0.7 degrees |
| a 6-axis arm of 0.4 m, 2 kg links on position motors (stiffness 4000, damping 200), a 6 kg payload for the last: each joint's error from its target after 4 s, mean and worst | 60 Hz | 0.8 / 1.4 degrees | 14 / 32 degrees |
| same | 30 Hz | 0.8 / 1.4 degrees | 16 / 36 degrees |
| an 11-body ragdoll (ball waist, neck, shoulders and hips with cones and twists, hinge elbows and knees) thrown down a flight of 8 stairs: the furthest any joint went past its limit over 5 s | 60 Hz | 1.5 degrees | 29 degrees |
| same | 30 Hz | 7.1 degrees | 19 degrees |
An articulation steps to the same Physics.stateDigest on native and in the browser, run after run, however the steps fall into frames and whatever contacts elsewhere came and went: the conditions the section on state digests states hold for it as for any body.
What it costs. The solver solves an articulation's coordinates together, so its cost grows faster than its link count. The solver's part of each step (Physics.stepCost().solverMs, the median over 4 s) for a chain of 1 kg ball links on 30 degree cones swinging at 60 Hz: 10 links 0.2 ms against 0.03 ms on impulse joints, 20 links 1.0 ms against 0.04 ms, and 30 links 2.7 to 3.1 ms against 0.06 ms (measured in the engine's development build on a heavily loaded desktop; budget a browser and a mobile device at two to four times as much). Every chain or limb hanging from one body is one articulation, rooted at that body, and costs what all their coordinates cost together: two chains hung from one beam are solved as one articulation of both. Keep an articulation to the tens of coordinates a limb, an arm or a ragdoll has (a ball joint is 3, a hinge or a slider 1), and build a long chain out of several articulations joined by an impulse joint, or of impulse joints with extra substeps on its own bodies (the section above).
Reading a joint's load: tension, compression, stress
Physics.jointReaction(joint) (or joint:reaction()) reads what a joint carried over the last physics step, averaged over the step: the force and the moment it applied to the body carrying it, and the same read the way a structure is read.
worldForce(N) andworldTorque(N·m) are the force on the carrying body and the moment on it about its anchor, in world space;localForce/localTorqueare the same along the joint frame's axes (X alongaxis);forceandtorqueare their sizes.axialis the force along this body as a member, at its end of the joint: positive pulls the end outward (tension), negative pushes it inward (compression). The member runs from the body's centre of mass out to its anchor (direction). A rod hanging a 10 kg block reads +98.1 N, the same rod propping the block from below -98.1 N.connectedAxialreads the connected body as a member the same way, so one joint answers for both members it joins.tensionis the force along the line between the two anchors, positive pulling them together: a rope's, cable's or winch line's tension, a spring's pull (negative while it pushes). It reads 0 while the anchors stand together, as a pin's do.shearis the force across the member,bendingthe moment across it,torsionthe moment about it (right-handed aboutdirection). A 2 m, 5 kg beam fixed by its root to a wall reads 49.05 N·m of bending at the root,worldTorquepointing along +Z for a beam standing out along +X: the moment that holds it up.loadis the share of the joint's break thresholds it stands at, the larger offorce / breakForceandtorque / breakTorque: 1 breaks it, 0 when it has neither.
Many joints in one call. Physics.jointReactions(joints) reads a list of Joints (or entities, for their unnamed Joint) and answers arrays in that order: axial[i], connectedAxial[i], tension[i], shear[i], bending[i], torsion[i], force[i], torque[i], load[i], exists[i] (false while that joint is not built). Physics.jointReactions(body) reads every joint a body is in, and Physics.jointReactions() every joint in the world; each joint is named by entityId (the entity its Joint is on, for a named Joint the one it was added to), joint, jointEntityId and connectedEntityId. { vectors = true } adds worldForce, worldTorque, localForce, localTorque, direction and position, and { fields = { "axial", "load" } } builds only the arrays it names. A structure read every frame is cheapest read by the joints' joint:jointEntityId() ids, taken once, and the fields it uses.
The peak between two reads. Physics.listenJointLoads(joints) keeps, for each joint, the largest load any step put on it until it is read: Physics.jointReaction(joint).peak is { force, torque, load, maxAxial, minAxial, step, steps } (the most tension, the most compression, and the step that carried the largest load), and jointReactions answers peakLoad[i], peakMaxAxial[i] and peakMinAxial[i] (the current reading for a joint nothing listens to). Reading takes the peak, so a load that crossed a threshold for one step and fell back is seen however many steps ran between two reads. Physics.listenJointLoads(joints, false) stops it; only listened and breakable joints are measured every step.
Colouring a structure by stress. A member pinned at two ends carries its axial load at both; the joints at each end each read a share of it (axial for the body carrying the joint, connectedAxial for the body it connects to), so a member's load is half the sum of every reading at its ends. bodyEntityId[i] and connectedBodyEntityId[i] name those two bodies, whichever entity each Joint sits on:
Physics.listenJointLoads(joints) -- the Joints the truss was built with
local function memberLoads()
local r = Physics.jointReactions(joints, { fields = { "axial", "connectedAxial", "bodyEntityId", "connectedBodyEntityId" } })
local axial = {}
for i = 1, r.count do
local a, b = r.bodyEntityId[i], r.connectedBodyEntityId[i]
axial[a] = (axial[a] or 0) + r.axial[i] / 2
axial[b] = (axial[b] or 0) + r.connectedAxial[i] / 2
end
return axial -- body entity id -> newtons, + tension, - compression
end
-- a colour per member: red pulling, blue pushing, deeper toward `limit` newtons
local colors = {}
for id, n in memberLoads() do
local t = math.clamp(math.abs(n) / limit, 0, 1)
colors[id] = if n > 0 then { 1, 1 - t, 1 - t } else { 1 - t, 1 - t, 1 }
end
A support post or a crate reads into the same table and is left uncoloured; a rope or a cable reads its own load as tension. For the member about to fail, read load (or peakLoad) per joint: it is measured against the same thresholds that break it. A body at rest falls asleep and keeps the reading of the step it fell asleep on; Physics.wakeUp keeps a structure being read awake.
Rails: a point held to a path (rollercoasters, trains, zip lines, sliding doors, sliders and tracks along a curve)
A rail joint holds a point on one body to a path on another: a coaster car on its track, a train or tram on its line, a trolley on a zip line, a door or a drawer on a curved slide, an elevator in its shaft, a bead on a wire, a camera dolly. The point is free to run along the path under gravity, contacts, forces and its motor, and held across it, through bends and vertical loops at speed.
-- a coaster car on a looping track: the points are in the track's own space
Physics.addJoint(car, track, { kind = "rail", path = trackPoints, closed = true, collideConnected = false })
-- a zip line whose trolley holds the line 1 m above its centre, with a little friction
Physics.addJoint(trolley, cable, { kind = "rail", path = { {0, 12, 0}, {15, 6, 0}, {30, 3, 0} }, localAnchor = {0, 1, 0}, friction = 0.02 })
-- a powered car: 8 m/s along the track, never pushing harder than 4 kN
Physics.addJoint(train, line, { kind = "rail", path = linePoints, motorMode = "velocity", motorVelocity = 8, motorMaxForce = 4000 })
- The path is
path, the points it runs through in the connected entity's local space (so a path on a moving body, a rail on a ship's deck, moves with it), or a spline frommodules.spline. It is a smooth curve through the points (curve = "linear"for straight runs between them), a loop withclosed = true. - The ends of an open path stop the point (
ends = "capped", the default) or let it run off (ends = "open"): the rail lets go andonPathreads false,leftnaming the end.joint:reattach()takes the point back onto the path's nearest point (move the body back to the path first). - The hold keeps the point on the path to within the solver's precision; a point found more than
tolerance(0.01 m) off it when a step begins (a body teleported by a script) is put back on it. A frictionless rail does no work, so a car keeps its energy round a loop at 30 or 60 Hz;frictionis a coefficient on the force holding the point to the path. A soft body rides a rail by the particlesregionnames ({ nearest = point }for one), held through the body's own give. - The motor holds a speed along the path (
motorMode = "velocity",motorVelocitym/s, positive toward the path's end) or brings the point to a place on it (motorMode = "position",motorTargetmetres from the start,motorStiffness/motorDamping), never pastmotorMaxForcenewtons.joint:setMotor(speed, maxForce)sets a velocity motor live. - Refused: a path that cannot be held (fewer than 2 points, or 3 for a loop, two consecutive points together, a point that is no position) or a field another kind takes (a spring's
stiffness, a rope'smaxDistance) is refused by name, as for every joint kind:Physics.addJointraises the reason and takes the Joint off the entity. - Reading it:
Physics.jointState(joint)readsprogress(metres from the path's start),speed,length,lapsround a loop,onPath,atEnd("start" / "end" while a capped end holds the point),offsetoff the path, the motor and friction forces, and the path'stangent,normalandcurvatureat the point.Physics.jointReaction(joint)reads the force holding the point (a car at the top of a loop at speed v reads m v²/r less its weight), withlocalForcealong the path, toward the bend's centre and across it.breakForcederails it above a force, with the break event every joint sends.
Every field is live: write path, closed, ends, friction or the motor on the running joint and the next step holds the point to that. Two points held on one track (a car's front and rear axles, each its own rail on the same path) keep a car pointing along it; the rails holding one body are solved together, and such a car gives up some of its energy to the solver (5 to 15% a minute round a loop with a vertical drop at 60 Hz), where a point held alone keeps it.
Breakable joints
A joint given breakForce or breakTorque releases the moment the reaction it is carrying exceeds either. The reaction is what the constraint solver actually applied over the step that broke it, in real units: a fixed joint holding a hanging 10 kg mass reads 98.1 N, a 20 kg mass 196.2 N, a 40 kg mass 392.4 N.
The two thresholds are independent, and they read two different things. breakForce is the size of the force the joint applies to the body carrying it, the force that holds its anchor to the other's. breakTorque is the size of the moment it applies about that anchor, in newton-metres: a joint holding a body still against a 30 N·m couple reads 30 N·m. Where the anchor sits decides how a load divides between the two: a 5 kg beam 2 m long fixed to a wall by its root reads its 49 N of weight as force and 49 N·m as moment at the root, while a block hung by a joint anchored at its own centre of mass reads its weight as force and no moment at all. So size a cantilever's root with both, and a hanging joint with breakForce. A joint given only one threshold can only break that way.
phys.addJoint("crate", { target = "wall", kind = "fixed", breakForce = 1200, breakTorque = 800 })
Physics.onJointBreak(function(e)
-- e.entityId, e.connectedEntityId, e.kind
-- e.force / e.torque — what broke it
-- e.impulse / e.angularImpulse — the reaction over the breaking step
-- e.position — where the joint's anchor was
spawnDebris(e.position, e.force)
end)
A joint reports once: the constraint is already released by the time the record arrives, and it stays released until something re-arms it. The Joint component carries the same event per joint (joint:onBreak(fn), joint:isBroken(), joint:breakEvent()) and joint:reattach() puts a broken one back — at the anchors it was authored with, so move the bodies back to where those anchors coincide before reattaching. A joint given neither threshold is never measured.
Breaks reach a listener after the physics step that broke the joint, before that step's fixedUpdate, whether the joint came from a Joint component or was written straight into the ECS as ecs.PhysicsJoint. A Joint costs nothing per frame while it holds.
Physics.jointBreaks() is the polling form for a script that would rather read than register; it returns everything that has broken since its own last call.
Size a threshold by measuring rather than guessing: Physics.jointReaction(id) reads the load a live joint is carrying right now, against the same quantities the thresholds are compared to, and its load is the share of them it stands at. Build the assembly, read the joint at rest, and set the threshold above that — then whatever you drop on it decides; Physics.listenJointLoads keeps the largest load between two reads for watching a structure come close. A sleeping body reports the last step that solved it and carries nothing new; Physics.wakeUp(id) puts it back under load.
One thing will surprise a threshold set by eye. A joint whose anchors do not line up at the moment it is created is violated, and the solver pulls the two bodies together with whatever it takes — a corrective load orders of magnitude above the resting one, which breaks any sane threshold on the first step. Place localAnchor and remoteAnchor so the two joint frames coincide where the bodies already stand.
Under multiplayer, the peer that simulates a body measures the loads on its joints and breaks them (see "Physics under multiplayer" below). A peer holding replicas of both bodies moves them along the simulating peer's poses, so the bodies part where that peer's break sent them; no break message crosses the wire. The Joint component's breakForce and breakTorque are synced fields, so every peer holds the same threshold.
Latches: hitches, couplers, docking ports, catches, magnets
A Latch is a latch point on a body: a trailer hitch, a coupler, a docking port, a door catch, a magnet, a socket a part snaps into. When two points that match come within reach, the physics step latches them and joins their bodies with a joint; a release, a broken joint or a removed point frees them, and a freed point latches again once it has stood clear.
The point is a frame: its entity's own frame moved by offset. Put it on the body, or on a marker entity under the body, at the place it latches and turned the way its partner will stand once joined. Two points latch when each accepts the other's tag (an empty accepts latches to its own tag), they stand within the larger of their radius, the turn between their frames is within the smaller of their maxAngle, and they close no faster than the smaller of their positive maxSpeed.
-- a ball hitch: back the trailer onto it and it hitches
hitch.component.add("Latch", { tag = "hitch", accepts = { "coupler" }, radius = 0.15, joint = { kind = "ball" } })
coupler.component.add("Latch", { tag = "coupler", accepts = { "hitch" } })
-- train couplers: one tag latching to itself, on contact at walking speed
car.component.add("Latch", { tag = "coupler", radius = 0.2, maxSpeed = 2, joint = { kind = "ball" } })
-- a docking port: only lined up within 10 degrees, pulled square by a fixed joint
port.component.add("Latch", { tag = "dock", radius = 0.3, maxAngle = 10, joint = { kind = "fixed" } })
-- a catch that bursts open past 2000 N
catch.component.add("Latch", { tag = "catch", accepts = { "strike" }, radius = 0.05, joint = { kind = "fixed", breakForce = 2000 } })
catch.component.get("Latch"):onRelease(function(e) if e.reason == "break" then print("burst open at", e.force, "N") end end)
The joint is a Joint named latch on the entity of the point that made it, built from the joint fields (the making point's, else its partner's, else a fixed joint), so every joint kind and field applies: a ball leaves a trailer free to swing, a hinge leaves one turn free, breakForce makes a catch that bursts. It holds the two frames together, point on point and turned alike, and reads like any joint (latch:latchJoint(), Physics.jointReaction, Physics.bodyState(id).joints). latch:release() (or Physics.releaseLatch(id)) takes it off; lock = "permanent" refuses that, so the latch holds until it breaks. latch:onLatch(fn) / latch:onRelease(fn) hear one point, Physics.onLatch(nil, fn) / Physics.onUnlatch(nil, fn) every latch in the world.
Latching runs after every physics step, at any tick rate: every point is placed on its body and sorted into a grid as wide as the widest reach, so a point costs the same however many others stand elsewhere, and a world with no Latch pays nothing. Pairs are taken nearest first, ties in the order the points' entities were made, so two freshly started engines latch the same pairs on the same step and their state digests agree. The latch is made on the peer that simulates both bodies; its Joint and each point's partner reach every peer, and two points whose bodies two different peers simulate do not latch.
Ragdolls: a character or creature carried by physics
animation.ragdoll(id) turns a skinned body into a ragdoll: its skeleton is carried by rigid bodies that fall, tumble and pose the mesh. It is the death, knockout, hit reaction, stunt fall or crash-test dummy of any rigged character, the built-in avatar included, and of any rigged creature. id is the skinned entity or any entity above it (a character root). The first call builds the ragdoll from the skeleton on the next frame, animation.ragdoll(id, false) included: its bodies then follow the animation until it is switched on, so its bones can be read and jointed first. animation.ragdoll(id, false) hands the body back to its animation and animation.ragdoll(id) ragdolls it again. A ragdoll poses the body whatever animates it (a clip player, an animation graph, a locomotion program, an engine AnimGraph component), and hands it back to the same driver.
Getting up. Handed back, every bone moves from where the ragdoll left it to the pose its animation holds (a body nothing animates goes back to the pose it held when it fell) over blend seconds of simulated time (0.5 unless the call states it; 0 hands it back in one frame), and the entity the call names (or the nearest one above it that also holds the skeleton's bones) is moved so the body stands up where it lies: the standing hips over the place the hips lie, turned about the vertical the way the lying body is turned, on the ground the body lies on. Play a get-up clip on the body as you hand it back and the body rises into that clip; standUp = false leaves the named entity where it is (a respawn that places the character itself). animation.ragdollState(id).blend reads how far the bones have come back (0 to 1), nil once they are there.
-- the enemy collapses where it stands
animation.ragdoll(enemy.id)
-- and gets up again where it lies, rising into its animation over half a second
animation.ragdoll(enemy.id, false)
-- a slower rise
animation.ragdoll(enemy.id, { active = false, blend = 1.2 })
What it is built from. A humanoid (a body with a humanoid role map: the built-in avatar, any imported humanoid rig) gets bodies sized for each body part (boxes for the torso, a sphere for the head and each hand, capsules for the limbs; the neck, collarbones and toes move with the body above them) and anatomical joints: hinges at the elbows and knees that bend one way, cones at the shoulders, hips, wrists, ankles and neck, a stiff spine. Each part weighs its share of a human body (the trunk about half, a thigh a tenth, a hand under one percent). Any other skeleton (a quadruped, a bird, a snake, a tail, a robot arm) gets a capsule along every bone that reaches a child bone, unless it is shorter than 15% of the skeleton's longest bone, and a ball joint that swings 45 degrees and twists 30. Bodies weigh 1000 kg per cubic metre of collider (about 120 kg for the built-in avatar, whose colliders are drawn generously: pass mass = 75 for a person of a set weight), the joints go limp, and two bones that are jointed together, or that already overlap in the bind pose, never collide with each other. A ragdoll's bodies take 12 solver iterations beyond the world's own, so its joints keep close to their ranges through a fall; how closely a long chain of limited joints holds under a hard impact is still the solver's (a wrist or an ankle can turn past its range for a few steps at 30 Hz and 4 substeps before it comes back).
Describing it. The options table states what the default does not:
animation.ragdoll(dummy.id, {
mass = 75, -- the whole body; the bones without a mass of their own share it
bones = {
head = { mass = 5, swing = 30, twist = 15 }, -- a heavier head, a stiffer neck
leftleg = { hinge = { -120, 0 } }, -- the left knee bends 120 degrees
spine = { strength = 40, damping = 6 }, -- a torso that holds itself up
Tail3 = { shape = "capsule", radius = 0.04, length = 0.3 },
HairBone = { shape = "none" }, -- no body: it moves with the bone above
},
})
A bone is named as the skeleton names it, or on a humanoid by its humanoid role, so one description fits every humanoid rig: hips, spine, chest, upperchest, neck, head, and for each side leftshoulder, leftarm (upper arm), leftforearm, lefthand, leftupleg (thigh), leftleg (shin), leftfoot, lefttoebase (right... the same). animation.ragdollState(id).bones lists each bone's name and role.
A bone takes shape (capsule, box, sphere, or none for no body), radius, length (along the bone) and size = {x, y, z} (a box, y along the bone) in metres, mass in kilograms, and for the joint holding it to the bone above: joint (ball, hinge or fixed), swing (a ball's cone half-angle) and twist (either way about the bone) in degrees, hinge = {min, max} in degrees (positive bends the bone's far end the way the skeleton faces: a knee's range is negative, an elbow's positive), strength (how hard the joint pulls the bone back toward its bind pose, an acceleration per radian; 0 is limp) and damping (how hard it resists turning). A description different from the last one rebuilds the ragdoll.
Part of a body. limp names the bones that go limp, each with every bone below it, while the rest keep following the animation: an arm hit by a shot hangs while the character keeps running.
animation.ragdoll(hero.id, { limp = { "leftarm" } }) -- the left arm hangs
animation.ragdoll(hero.id, { limp = { "hips" } }) -- the whole body, from the hips out
Reading it back. animation.ragdollState(id) answers { built, active, blend, mass, bones, problems, replication }: every bone body with bone, role, id, parent, its shape and size in metres, its mass read off the solver, whether it is simulated, and its joint (kind, swing, twist, hinge, strength, damping). built is false until the frame after the call. problems names anything the description asked for that the skeleton could not give (a bone it does not have, a size that is not positive). replication is how the ragdoll travels between peers (see "Physics under multiplayer"), nil outside a session.
Every bone body is a body. Each bone's body is the body of that bone's own armature entity (bone.id, or animation.ragdollBone(id, "head")), so every Physics call takes it, with its frame centred on its collider and +Y along the bone:
local dummy = crashTestDummy.id
animation.ragdoll(dummy)
-- the frame after: read each bone like any body
local head = animation.ragdollBone(dummy, "head")
print(Physics.getVelocity(head), Physics.bodyState(head).mass)
for _, c in Physics.contacts(head) do print("head hit", c.other, c.totalImpulse) end
-- a hit at a point knocks one limb
Physics.applyImpulseAtPoint(animation.ragdollBone(dummy, "leftarm"), { x = 0, y = 0, z = 40 }, hitPoint)
-- hang the body from a ledge by one hand, until the grip gives
local hand = animation.ragdollBone(dummy, "righthand")
local grip = Physics.addJoint(hand, ledge, { kind = "ball", breakForce = 1500 })
Physics.onJointBreak(function(e) if e.entityId == hand then print("let go") end end)
A ray or a contact on a ragdoll names the bone's entity; a listener on the skinned body (Physics.onContact(body, fn)) hears every bone's contacts, and Physics.ignoreCollision(body, other) keeps every bone apart from other. For the load a crash puts through a body, listen to its bones' contacts (Physics.onImpact, Physics.contactPeak) and read each bone's acceleration with Physics.probeMotion.
Physics under multiplayer
One peer simulates each synced body: its owner, or for an entity nobody owns, the peer that announced it into the room (an ownership claim moves the body to the claimer). Every other peer holds a replica that shows the body where the simulating peer puts it:
- A rigid body that is
dynamicmoves on a replica as a kinematic body along the poses the simulating peer sends, so it pushes the local bodies it meets and is not pushed by them.Physics.kindstill readsdynamicthere. A body handed to this peer by a claim simulates from where it stands, moving as it was moving. - A soft body keeps its elastic motion on a replica, held to the simulating peer's pose, and takes its permanent deformation from that peer: a dent the owner makes reaches every peer and a peer that joins later, and a replica never dents on its own. Tearing is the simulating peer's too: its solver tears the body, a replica tears nothing of its own, and a cut or tear a script asks of a replica is left to the simulating peer. The elements its flow changed travel with its dent, so a replica settles under the same loads into the shape the simulating body settles into, a shell that never sleeps on its chassis included; when the body comes to rest the simulating peer states where each of its particles settled, so every peer, and every peer that joins later, holds the shape it settled in particle for particle, and keeps it at rest. A body handed over by a claim keeps its dent and flows from there. A pinned body is carried with its pins. A body whose particles are tied to a rigid body (
attachments) ties the same particles at the points of that body the simulating peer ties them at, whenever it was built, so it hangs from the rigid body's replica as it hangs on the simulating peer; it moves with that replica, a jump to the simulating peer's pose included, and keeps its own elastic motion relative to it. - A ragdoll (
animation.ragdoll, whole orlimplimbs) is simulated by the peer that owns the synced entity at or above its skinned body (a character's synced root): that peer's request (on or off, the limp bones, the description) reaches every peer and every later joiner, and every other peer shows the ragdoll with its bones where the simulating peer's bone bodies stand, drawn a short delay behind them and interpolated, as a moved entity is (sync.interpolation_delay,multiplayer.setSmoothingon the root). On those peers the simulated bones are kinematic bodies at those poses, so they push what they meet there. Claiming the root hands the ragdoll over: the new owner simulates it from where it lies. A bone pose travels in 22 bytes (about 400 bytes a tick for the built-in avatar while it moves, nothing once it rests), andanimation.ragdollState(id).replicationreads which peer simulates it (authority,owner), when its state last crossed the wire (lastSync) and what it costs (bytesPerSecond).
The pose travels on every change and once more, reliably, when the body comes to rest, so the place a body settles at is the place every peer and every later joiner holds. While a soft body flows its dent travels as the particles whose rest place moved (10 bytes each) and the elements its flow changed (22 bytes a flowed cell, 6 an edge or fold); once it comes to rest it states, once, every particle's settled place as well (6 bytes a particle), about 7 KB for a dented 64-particle box. A statement of a body tied to rigid bodies carries its ties (18 bytes a tied particle), and a tied body that never flows states them once. Shape statements are paced to about 2 KB a second per body, and a body at rest costs nothing. Physics.softBodyState(id).replication reads which peer simulates the body (authority: "local" or "remote", and owner), when its state last crossed the wire (lastSync, seconds) and what it costs (bytesPerSecond).
A force, impulse or velocity written to a replica changes nothing the room sees: a rigid replica does not take it, and a soft replica wobbles from it on this peer alone, held back to the simulating peer's pose and keeping no dent. Push a body from the peer that simulates it, or claim it first (multiplayer.claimOwnership(id)).
Replays: recording the simulation and watching it again
An instant replay, a crash replayed in slow motion from another angle, a kill cam, a ghost car, a scrubbable timeline with plots beside it: each is a stretch of simulation recorded as it ran and drawn again. Physics.recordReplay records it, Physics.playReplay plays it back.
Physics.recordReplay({ seconds = 10 }) -- keep the last 10 s, every step
-- ... the crash happens ...
engine.paused = true -- hold the live simulation where it is
Physics.playReplay({ rate = 0.25 }) -- the last 10 s at quarter speed
Physics.playReplay({ time = 3.2, rate = 0 }) -- scrub: hold the moment 3.2 recorded seconds in
Physics.playReplay({ rate = -1 }) -- backwards at full speed
Physics.playReplay(false) -- back to the live simulation
engine.paused = false
What a recording holds. At the end of every step: each rigid body's and ragdoll bone's pose and linear and angular velocity, each soft body's pose with its particles' positions and velocities, and each moment two colliders of the recorded entities began or stopped touching (Physics.replayContacts: who, where, the normal, the impulse, the closing speed). By default it records every entity whose body moves (dynamic and kinematic bodies, ragdoll bones, soft bodies); entities = { ... } records just those, of any body type. It keeps the most recent seconds (30 by default) inside maxBytes (64 MiB by default) and lets the oldest steps go past either, so a game can record from the start of play and replay the last few seconds whenever something worth watching happens. It records at the step rate, in play and while Physics.advance steps; contacts = false leaves the contacts out. A recording belongs to the play session it ran in: leaving play stops it and ends a replay playing it, and what it holds stays to play, read and save until a new recording starts, so a component that starts recording in start() starts a fresh one each play session.
What playing draws. Every recorded entity is drawn where it was at the replay's time, blended between the two recorded steps either side of it, so a quarter-speed replay of a 60 Hz recording moves smoothly through each step rather than jumping from one to the next. Whatever rides on a body (its wheels, a model parented under its collider) moves with it, a soft body takes the shape its recorded particles held, and an active ragdoll's bones their recorded poses. rate is recorded seconds per second: 1 is real time, 0.25 slow motion, negative backwards, 0 holds the frame. time jumps anywhere between Physics.replayInfo().from and .to (the recorded seconds of the first and last kept steps), and loop = true wraps around. The replay moves on the frame clock, so engine.timeScale leaves it alone.
The live simulation is untouched. Playing draws the recording and writes nothing into the simulation: every body, velocity and particle stays the live state, and every read of a body (entity.position, Physics.softParticles, Physics.stateDigest) answers that live state. A ragdoll's bone entities follow how the ragdoll is drawn, so while a replay plays they hold the replayed poses, and the live ones again once it ends. With engine.paused = true the simulation holds still under the replay, and Physics.stateDigest() reads the same digest before the replay as after it; with gameplay running the simulation steps on underneath (a kill cam over a match that carries on). A recording that is still running while it plays keeps recording, so the next replay holds the newest steps.
Any camera. The replay is drawn into the world, so every camera sees it: the editor camera, a scene camera placed for the shot, a camera orbiting the wreck. Physics.drawnPose(id) answers the replayed pose (replayed = true), and the camera rigs that follow a body's drawn pose (the Controllers library's chase, orbital_follow, cinematic and the others listed under "Where a moving body is, and where it is drawn") follow it through the replay. In the editor, play held with engine.paused = true draws the viewport from the editor's fly camera; camera.setEditorOverride(id) gives a replay camera the viewport while the replay plays, and camera.setEditorOverride(nil) hands it back (the topics/cameras guide).
local info = Physics.replayInfo()
print(info.duration, info.steps, info.bytes, info.bytesPerSecond, info.recordMs)
-- a ghost: put a marker where the car was 2 s into the recording
local f = Physics.replayFrame({ time = info.from + 2 })
marker.position = f.bodies[car].position
-- the hits, for sounds and sparks timed to the replay
for _, c in Physics.replayContacts() do
if c.kind == "begin" and c.impulse > 50 then print(c.time, c.a, c.b, c.impulse) end
end
Physics.replayFrame({ time }) reads what a replay draws at that second: bodies[id] (id/bone for a ragdoll bone) with position and rotation, and softBodies[id] with its entity's pose (the pose entity.rotation reads live, where the body's frame carries the entity) and each particle's world position, one vector per particle in the order Physics.softParticles reads them, which is where a squash or a stretch is measured from; velocities = true adds the velocities. A soft body's frame is the write Physics.setSoftParticles takes: { positions = f.softBodies[id].particles, velocities = f.softBodies[id].velocities }.
Keeping a recording. Physics.saveReplay() returns the recording as a string of bytes, the same on every platform, and Physics.loadReplay(bytes) takes one back, so a recording made in a native engine plays in a browser engine and the other way round. It names its entities by id, so it plays over the scene it was recorded in; while it plays, Physics.replayInfo().missing lists the recorded tracks the scene holds nothing to draw on (an entity id it does not hold, or a soft body of another particle count), which stay drawn where the live simulation holds them. Physics.loadReplay refuses bytes that are not a whole recording, naming what they lack.
vfs.write("/source/replays/crash.replay", Physics.saveReplay())
local data = vfs.read("/source/replays/crash.replay")
if data then
Physics.loadReplay(data)
Physics.playReplay({ rate = 0.5 })
end
Going on from a recorded moment. Physics.resumeReplay(time) ends the replay and writes the state recorded at time into the simulation: each rigid body's pose and velocities, and each soft body's particle positions and velocities. The simulation steps on from there once gameplay runs: an undo in a puzzle, a retry from just before the crash. Ragdoll bones, joints' carried impulses and a soft body's plastic flow carry on from the live state, and the solver starts from the written state alone, so a resumed run follows the original closely rather than to the bit ("Pushing, hitting and pinning a soft body from code" says the same of a soft body written back).
What it costs. Memory grows with the bodies and particles recorded and the step rate: a rigid body takes 13 numbers a step and a soft body 7 plus 6 per particle, four bytes each. maxBytes bounds the steps and the contacts kept with them, and a recording lets go of a body that came and went once no step it keeps holds that body. Physics.replayInfo().bytesPerSecond reports it for the recording at hand, and recordMs / recordMsMax what recording took a step, which the profiler shows as system.schedule.logic.physics_step.replay. Measured in the engine's development build on a heavily loaded desktop, 10 s at 60 Hz of 20 boxes tumbling and a 448-particle soft cube crushed among them came to 600 steps, 7.3 MB (about 730 KB per recorded second, 7.2 MB saved) and 0.1 to 0.3 ms of recording a step on average, beside a step of about 2 to 4 ms. Playing it back cost about 0.02 ms a frame to move the replay on and sample it (system.schedule.pre_update.advance_physics_replay) and 0.01 ms to draw it (system.schedule.render.draw_physics_replay), and the drawn poses were the recorded ones exactly, at 0.25x and 1x.
State digests and determinism
Physics.stateDigest() hashes the whole simulation as it stands into sixteen hex digits: every rigid body's type, position, rotation, linear and angular velocity and sleep state, every joint's carried impulses (what the solver warm-starts the next step from) and whether it is enabled, and every soft body's particle positions and velocities. Two engines whose digests are equal hold the same state, so a native player and a browser player, two peers on one world, or two runs of one scripted scene check that they agree by comparing sixteen characters instead of every pose. A replay, a ghost car, a verified leaderboard run or a "the same bridge breaks at the same member everywhere" test all start from this check.
-- One digest, now.
local d = Physics.stateDigest()
print(d.step, d.digest, d.bodies, d.joints, d.particles)
-- The state this game owns, keyed by name so two engines that each spawned the scene line up.
local mine = Physics.stateDigest({ entities = { bridge, truck, deck1, deck2 }, key = "name" })
-- Every step's digest, as the step leaves it.
Physics.recordDigests({ steps = 1800, entities = ids, key = "name", values = true })
-- ... run the steps ...
local log = Physics.digestLog({ frames = true }) -- { steps, digests, frames }, each frame with its entries
What is hashed, and how. Each body, joint and soft body is an entry named by its entity: by id (key = "id", the default, which every engine bound to one world shares) or by name (key = "name", which engines that each built the same scene share; spawn the scene with names unique to it). Ragdoll bones are named <entity>/<bone> and joints <entity>/<joint name>. The entries are hashed in the order of their key, so the digest depends on the state alone, and it is the same value on every platform for the same state. Each value is hashed as the exact bits of its 32-bit float; quantum = 1e-4 instead hashes the whole number of tenth-millimetres (or whatever the unit) nearest it, so two states closer than that read alike. entities limits the digest to the entities a game owns, so the rest of the world (an editor gizmo, another game in the same world) does not enter it.
Finding where two runs parted. A digest tells whether two states agree; Physics.firstDivergence(a, b) tells where they stopped agreeing. Give it two stateDigest results, or two digestLog results read with frames = true: it walks the logs step by step from their first recorded step (so two engines that started recording at the same point line up whatever their own step numbers), and answers the first index whose digests differ, the first body, joint or soft body (in hash order) whose own digest differs there, and, when the recording kept values, the field and component and both values:
local d = Physics.firstDivergence(logFromPeerA, logFromPeerB)
if d then print(d.index, d.step, d.kind, d.key, d.field, d.axis, d.a, d.b) end
-- 37 1412 body bridge_deck7 angvel z 0.031250 0.031249
local big = d and d.largest
if big then print(big.key, big.field, big.axis, big.delta) end
-- bridge_deck3 linvel y 1.4852
The first entry in hash order is often a body that moved by its last bit only because the cause pushed it a step later in the same solve. largest names the value that differs the most at that step across every entry that kept values (its kind, key, field, component, axis, both values and delta), which is usually where to look first.
A log of a few hundred steps of digests is a few kilobytes, small enough to send to a peer (multiplayer messages) or write to a file. With entries and values each step also keeps every entry's numbers, about 60 bytes a body, so keep steps as short as the run you compare; past 64 MB the oldest steps go first.
What it costs. A digest reads every covered body once and sorts the entries by key. Measured with 200 bodies in the engine's development build on a heavily loaded desktop, a call from Luau takes about 0.05 to 0.1 ms over the whole world, 0.07 to 0.11 ms with the 200 entities named in entities, 0.23 to 0.33 ms with entries and 0.65 to 0.93 ms with values, most of the difference being the Luau table the call returns. A recording takes the digest inside the step and builds no table: about 0.15 to 0.22 ms a step over the same 200 bodies, whichever of the digests, the entries or the values it keeps. The profiler reports it as system.schedule.logic.physics_step.digest, and a step with no recording running takes none.
When two engines reach the same state
The digest checks determinism; the solver and the engine supply it. The engine builds rapier, its solver, in its cross-platform determinism mode: every step does the same floating-point arithmetic on every target, takes the angle of a joint at its limit and every other transcendental function from one pure-Rust math library, and walks its internal tables in the order they were filled. The engine hands the solver the bodies (ragdoll bones among them), colliders, joints and soft bodies a frame builds in the order their entities were spawned, and the solver puts each new one in the lowest slot free, so a scene a script spawns takes the same places in the solver whatever was created and removed before it ("The same scene, built the same way" below). The same simulation therefore steps to the same bits on a native engine (x86-64) and a browser engine (WebAssembly with SIMD). Measured:
- A scene of a box stack on a triangle-mesh ground, tumbling balls and capsules, a chain on ball joints, a motor-driven hinge pushed against its limits, a slider on a spring motor and a small fast ball under continuous collision reaches the same digest after 240 steps on x86-64 and in Chrome. Without the determinism mode the two part.
- Soft bodies on the default solver whose cells flow plastically (
plasticYield), struck by a dropped rigid box and pressed into each other, reach the same digest on x86-64 and in Chrome, and on one, eight or no solver threads. A plastic soft box under a 30 kg box dropped from 9.5 m, beside two rigid boxes, records the same digest at every one of the 120 steps after the blow on a native and a browser engine bound to one world, twice on each. - One script (a floor, a stack of four boxes, a ball and a capsule set spinning, and a chain of four links on ball joints hanging from a post, built while the simulation is paused) starts from the same digest and records identical digests at every step compared, 371 to 375 steps, in two freshly started native engines, in a native engine bound to a world and in a browser engine bound to that world, twice in the browser.
- A native and a browser engine bound to a world whose starting scene holds a dynamic body have recorded such a script identically for 45 steps and parted from the 46th; each platform repeats its own result exactly. So a native and a browser engine compare on a world whose scene starts with no body, and engines of one platform compare on any world.
What the mode costs the step, measured on the solver alone: the median step of 200 awake boxes tumbling in a pile of about 600 touching pairs at 60 Hz, twelve runs each, natively (x86-64, optimised) and in Chrome (WebAssembly with SIMD), on a desktop under a load average of 100 to 160. Natively 0.21 to 0.42 ms without it (median of the runs 0.33 ms) and 0.28 to 0.59 ms with it (0.35 ms); in Chrome 0.49 to 1.2 ms without it (0.71 ms) and 0.46 to 0.99 ms with it (0.54 ms). The difference lies inside the spread between runs on both targets, so no cost of the mode shows in that measurement.
Two engines reach the same state under these conditions:
- The same engine build. A different engine version steps differently.
- The same settings and tick.
physics.tick_rate,physics.solver_iterationsand every otherphysics.*setting equal on both, and the same number of steps between the same inputs. A frame-rate difference does not matter: steps are fixed, and a force written from frame-time code is spread over the steps the frame runs (see "A force over time"), so writing inputs from step hooks (Physics.onBeforeStep) is what keeps them on the same steps everywhere. - The same scene, built the same way. The solver orders its work by the slots its bodies, colliders, joints and soft bodies occupy. Each new one takes the lowest slot free, and the engine hands the solver what a frame builds in the order its entities were spawned, so the order earlier bodies were created and removed in leaves nothing a later scene steps by: a level restarted in the same session or in a new play session, and a peer that played another level and removed it first, build the scene as a freshly started engine does and step it to the same bits. Measured, with the scenes run in a different order in each engine: a span of ten planks on fixed joints between two anchors, sagging under gravity beside a box sent into a row of three, read the same digest after 240 steps on five runs in one engine and on two runs in each of two other engines; a box riding a platform a before-step hook drives read the same digest after 120 steps on every run in three engines, whether the advance ran in one frame or was spread over many; a floor, a stack of three boxes, a ball and a three-link chain on ball joints, recorded for 90 steps, despawned and built again, recorded the same 90 digests (
Physics.firstDivergenceanswers nil) whether advanced or run in real time; and a 40-segment rope with a crate tied to its end, despawned and built again, read the same digests on both soft-body solvers. - The same inputs in the same order, on the same steps. Forces, impulses, velocity writes, spawns and despawns at the same step on both sides. Build a compared scene while the simulation is paused and start the recording before unpausing it, then check that
Physics.stateDigest().stepread before and after the build is the same step: a step taken while the bodies were still being built puts each engine's scene at a different point when the recording starts. - A scene put back where it started steps from where it was put. A dynamic body whose position or rotation a script writes is placed there: the next step drops every contact the body held, with the impulses the solver carried in them into its next solve, finds the body's contacts where it now stands the way the first step after a build finds them, and starts over the measure of how still the body has been, which decides the step it falls asleep on, the way a built body starts it. So a level restarted by writing every dynamic body back to where it was built (its
positionandrotation,Physics.setVelocity(id, 0, 0, 0),Physics.setAngularVelocity(id, 0, 0, 0), thenPhysics.wakeUp()) and given the same inputs steps as its first run did, bit for bit, and so does a run that starts by writing every body to a state it wrote before. A write puts back the poses and velocities and nothing else the solver carries: a scene that ran before the moment its start was read held contacts there, joint impulses, soft bodies' shapes and flow, vehicles' wheel state, and a run from a moment like that comes back to the bit only throughPhysics.snapshotandPhysics.restore(the next section), which put all of it back. Take the snapshot when the moment to return to is not the build itself (a checkpoint, the instant before a crash, the bridge as it stands after an edit). Measured on a native engine: a 3x3 stack of crates on a floor struck by a ball at 30 Hz, put back twice and struck again, recorded the same 90 digests on all three runs, and so did a stack, a ball and a three-link chain on ball joints at 60 Hz; a 2x4 stack whose bodies were written back before each of three runs at 60 Hz recorded the same 90 digests on every run; and two crates stacked at rest with sleeping allowed, written back after they fell asleep, recorded the same 60 digests on all three runs, falling asleep on the same step each time. The 3x3 stack's state read 20 steps into a run and written back by hand parted from that run on the first step after, and a snapshot taken at that step and restored did not. A browser engine recorded the same: the 3x3 stack put back twice and the 2x4 stack written back twice each matched its first run at every step, and the two crates at rest fell asleep on the same step after each write as after their build, with the digests a native engine read. - Nothing else in the scene's way. A body the comparison leaves out of
entitiesstill pushes the bodies it touches: a scene built where the world's starting scene already holds a body (a new world's crate stands near the origin) takes that body's history into its own, so build a compared scene clear of other bodies, or keep them in the comparison. - Vehicles step their wheels in the order the wheels arrived. Each vehicle works and sums its wheels' suspension, drive and tyre forces in the order its wheels were spawned, whatever entity slots they were given; that is the order
Physics.vehicleStatelists them in, and each wheel's place in it is itsvehicleOrder. So a car built again over the slots another scene freed steps as its first build did. Measured: a 600 kg car on fourWheelColliderwheels driven by a motor on one pair, and the same car with its front wheels steered and all four driven through aShaftNetwork(an engine, a centre and two axle differentials), each built, advanced 300 steps at 30 Hz and despawned twice in each of three freshly started native engines (the starting scene's crate removed), read one digest per car on every build in every engine, five rebuilds in one engine read it again, and a browser engine bound to a world read the same two digests. - The same worker count, for soft bodies on the FEM solver. Rigid bodies, contacts and joints come out the same on any number of workers; a soft body with
solver = "fem"steps differently on a different number, so two machines with different core counts can part there.
Under multiplayer the peer that simulates a body is the authority for it (see "Physics under multiplayer"), so peers on one world do not need to agree for the room to look right; a digest over the bodies each peer simulates is how a non-owner checks the owner's result, or how a test asserts two engines stepped the same.
Snapshots: put the whole simulation back to a moment
Physics.snapshot() takes the whole simulation as it stands between two steps, and Physics.restore(snapshot) puts it back: every rigid body (pose, velocities, sleep), collider, joint (limits, motors, the impulses it warm-starts from, and whether it broke), soft body (particles, elements, the plastic dents it took), the islands, every contact with the impulses it carries into the next step, the continuous-collision state, the vehicles and their wheels, the drivetrains, the forces bodies hold, the plane holds, every rail's point (where it stands on its path and the laps it ran), the centre of mass and inertia stated for each body, the push of the air and water each sleeping body rests under, and every entity's transform and velocity with the settings of the components the solver is built from: Physics, Joint, the collider (BoxCollider, SphereCollider and the other shapes), SoftBody, CollisionGroup and PlaneHold, every component declaring simulation = "physics". A setting written between the snapshot and the restore (a mass, a friction, a joint limit, a soft body's stiffness) reads back the snapshot's value after it, the value the solver simulates with, and a later write of the newer value reaches the solver again. The steps after a restore run the same arithmetic on the same values as the steps after the snapshot was taken, so N steps after a restore reach the state N steps after the snapshot reached, bit for bit (Physics.stateDigest reads the same digest), however many times it is restored. That is the loop of a bridge builder (build, test, reset, edit, test again), a crash test (retry from the moment before impact), a puzzle's undo, and a "from this exact state, does the tower fall?" check. A scene of rigid bodies put back to the moment it was built needs no snapshot: writing each dynamic body's pose and velocities back steps it as its first run did ("When two engines reach the same state" above). A snapshot is what returns to any other moment, and to everything beside the poses and velocities.
-- Build the bridge, then test it as often as you like.
local built = Physics.snapshot()
Physics.advance({ seconds = 10 }) -- the truck crosses; three members break
print(Physics.stateDigest().digest)
Physics.restore(built) -- the bridge stands as built, broken members back
Physics.advance({ seconds = 10 }) -- the same run again, to the same bits
print(built:size(), built:info().bodies) -- bytes it is saved as; what it holds
built:save("/zero/source/saves/bridge.physics")
local again = Physics.loadSnapshot("/zero/source/saves/bridge.physics")
Physics.restore(again)
built:release() -- its memory goes now, not when it is collected
What a restore needs. The world has to hold the bodies the snapshot was taken over: the same entities, each with the same bodies, colliders, soft bodies and joints. Where the solver built them does not matter: a world that built the same scene in another order, or after other bodies came and went, restores the snapshot and steps on to the same digests the world it was taken in reaches. A restore into a world that changed is refused, changing nothing, and the error names every entity in the way: one gone since the snapshot, one that has a body the snapshot does not hold (made since: remove it before restoring, or take a new snapshot after making it), and one whose bodies, colliders or soft body differ from the snapshot's (one removed or added since, or built again from another collider shape or into a soft body of other particles, such as another resolution or shape), and one carrying a component the solver is built from that it did not carry then, or no longer carrying one it did. A joint that broke since the snapshot is part of what it holds, and comes back; a wheel that came off its vehicle since goes back on. A piece a soft body tore off since is an entity made since: remove it before restoring, and the torn body comes back whole. So the bridge builder takes a new snapshot after each edit and restores it after each test.
What stays as it is. Forces, drives and kinematic moves a script queued for the coming steps stay queued; listeners, digest recordings, replay recordings, motion probes and step hooks keep running; the step counter keeps counting (restore answers the step the snapshot was taken at and the step the world now stands at). Settings (physics.*) and content-defined gravity fields, water, winds, the air's density and surfaces are the world's own and are not part of a snapshot, and so are the components the steps read as they run (FluidForces, Force, LiftSurface, WheelCollider): each keeps the value it holds, and the steps after the restore simulate with it, and waves and gusts stand at the world's moment, which a restore leaves where it is.
Saved snapshots. snapshot:save(path) and snapshot:bytes() give a versioned, little-endian format, the same on every platform, and Physics.loadSnapshot reads one back on this engine or another (native or browser) that holds the same bodies. A snapshot names its entities by id, so it restores in an engine bound to the same world whatever order that engine built the scene in; one whose entities are missing there is refused, naming them. A snapshot taken while a soft body is tearing holds pieces still waiting for their entities, and saving it is refused until a snapshot is taken once that frame is done.
What it costs. Live snapshots together hold at most 1 GiB; past it, taking another is refused until older ones are released or collected. snapshot:info().ms is what taking it took and restore(...).ms what the restore took.
The full surface
lsp.methods("Physics") lists every Physics method with its signature; zero phys (or search_tools) surfaces the phys toolbox verbs. The model to hold: phys composes from the tool surface, Physics controls from code, and simulation happens in play.