physics
Lowercase alias of Physics. Same identity (#565). Prefer this in new code so the convention matches entity, scene, cam, ...
physics: any
The physics namespace: 165 functions.
globals/physics/COLLIDER_COMPONENTS
physics.COLLIDER_COMPONENTS()
Every collider component, in the order a lookup walks them. Shape is the component's identity, so code that works on "whatever collider this entity has" walks this list rather than guessing a shape.
for _, name in ipairs(Physics.COLLIDER_COMPONENTS) do ... end
globals/physics/addCollider
physics.addCollider(entityId: string | entityRef, component: string, config: table?)
Add a collider component to an entity, naming the shape you want.
Parameters
entityIdstring | entityRef— Target entity id.componentstring— One ofPhysics.COLLIDER_COMPONENTS.configtable(optional) — The component's own fields, e.g.{ radius = 0.5 }for a sphere.
Physics.addCollider(id, "SphereCollider", { radius = 0.5 })
globals/physics/addConstraint
physics.addConstraint(entityId: string | entityRef, opts: table?)
Add a transform constraint to an entity.
Parameters
entityIdstring | entityRef— Target entity id.optstable(optional) — Optional constraint description (targetEntityId, position, rotation, scale, lookAt, targetPosition, axes, weight).
Physics.addConstraint(id, { targetEntityId = parent, position = true })
globals/physics/addJoint
physics.addJoint(entityIdA: string | entityRef, entityIdB: string | entityRef, opts: table?) -> any
Add a Joint component connecting two entities. Accepts either
vec3-style anchor inputs (localAnchor = {x,y,z}) or pre-split
scalar keys (localAnchorX/Y/Z); every other key is a Joint field or
name / enabled, which every component takes, and any other key
raises, naming it.
A body takes any number of joints: on an entity that already carries a
Joint the new one is added under name (or, without one, the first of
joint2, joint3, ... free on it), and each is its own solver joint.
An end entity that is no body itself joins the nearest body above it at
its own position and orientation, so a marker under a beam's end pins
the beam there: a truss is beams joined through end markers.
Parameters
entityIdAstring | entityRef— Entity that hosts the Joint component.entityIdBstring | entityRef— Connected entity.optstable(optional) — Optional joint description:kind(fixed, hinge, ball, prismatic, spring, rope, generic, rail),localAnchor,remoteAnchor,axis,remoteAxis,collideConnected, the limits (limitMin/limitMaxfor a hinge in degrees or a prismatic in metres,swingLimit/twistLimitfor a ball joint in degrees,axisLimitson any axis), the motor (motorMode"velocity" | "position",motorVelocity,motorTarget,motorStiffness,motorDamping,motorMaxForce,motorModel,axisMotorson any axis),lockedAxesfor a generic joint,stiffness,damping,restLength,maxDistance, the yield (yieldForcea rope pays out or a prismatic slides at,yieldTorquea hinge turns at, each holding again below it;reelSpeed, how fast a yielding rope winds in to a shortermaxDistance),breakForce,breakTorque,region,remoteRegion,articulated(a link of an articulation, solved in reduced coordinates: chains that do not stretch, limits that hold under load); a rail'spath(points in entity B's local space, or a spline),closed,ends("capped" | "open"),curve("smooth" | "linear"),toleranceandfriction. An articulated joint (articulated = true) makes entity A's body a link hanging from entity B's (or B's from A's, when A already hangs from a link or is not dynamic): the bodies articulated joints join form a tree, solved in reduced coordinates, so a chain does not stretch, every limit holds under load and a motorized arm tracks its targets. Build the tree from its root out or in any order; a joint that would close a loop is not built and names the loop in the Joint'serrors().Physics.articulationreads the tree. A rail holds the point atlocalAnchoron entity A topathon entity B: free to run along it under gravity and forces, held across it, read throughPhysics.jointState(progress,speed,onPath,atEnd) andPhysics.jointReaction(the force holding it,localForcealong the path, toward the bend's centre and across). Either end may be a soft body (an entity with aSoftBodycomponent):regionanchors this end on a region of entity A's soft body andremoteRegionthe other end on a region of B's, each asPhysics.softRegiontakes it ({ box = { min, max } }or{ nearest = point }); an end with no region is anchored on the soft body as a whole. The anchor of a region end is measured from the centre of its particles.
Returns any — The new Joint component (its live proxy), which every joint read and Physics.removeJoint take. A description the Joint refuses, of any kind (a rope with no maxDistance, a rail path that cannot be held or a rail given a spring's stiffness, a yield out of range or on a kind that cannot hold it), raises an error naming why, and the refused Joint is taken off the entity.
Physics.addJoint(a, b, { kind = "fixed" })
Physics.addJoint(a, b, { kind = "hinge", axis = {x=0,y=1,z=0} })
Physics.addJoint(door, frame, { kind = "hinge", axis = {0,1,0}, limitMin = 0, limitMax = 110 })
Physics.addJoint(arm, base, { kind = "hinge", axis = {0,0,1}, motorMode = "position", motorTarget = 90, motorMaxForce = 500 })
Physics.addJoint(forearm, upperArm, { kind = "ball", swingLimit = 45, twistLimit = 20, collideConnected = false })
Physics.addJoint(piston, cylinder, { kind = "prismatic", axis = {0,1,0}, limitMin = 0, limitMax = 0.5 })
Physics.addJoint(seat, rail, { kind = "generic", lockedAxes = {"linY", "linZ", "angX", "angY", "angZ"}, axisLimits = { linX = {-0.2, 0.2} } })
Physics.addJoint(a, b, { kind = "rope", maxDistance = 8 })
Physics.addJoint(hook, load, { kind = "rope", maxDistance = 4, yieldForce = 3000 })
Physics.addJoint(car, track, { kind = "rail", path = trackPoints, closed = true, collideConnected = false })
Physics.addJoint(trolley, cable, { kind = "rail", path = { {0, 12, 0}, {15, 6, 0}, {30, 3, 0} }, localAnchor = {0, 1, 0}, friction = 0.02 })
Physics.addJoint(door, frame, { kind = "rail", path = arcPoints, motorMode = "position", motorTarget = 1.2, motorMaxForce = 300 })
Physics.addJoint(a, b, { kind = "fixed", breakForce = 1200, breakTorque = 800 })
Physics.addJoint(bag, hook, { kind = "ball", region = { nearest = {0, 0.5, 0} } })
Physics.addJoint(jellyA, jellyB, { kind = "fixed", 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} } } })
local grab = Physics.addJoint(hand, crate, { kind = "fixed", breakForce = 2000 }); Physics.removeJoint(grab)
for i = 2, #links do Physics.addJoint(links[i], links[i - 1], { kind = "ball", articulated = true, swingLimit = 30, collideConnected = false }) end
Physics.addJoint(forearm, upperArm, { kind = "hinge", axis = {0, 0, 1}, articulated = true, limitMin = 0, limitMax = 140, motorMode = "position", motorTarget = 45, motorMaxForce = 400 })
globals/physics/addVelocity
physics.addVelocity(a: string | entityRef | number | vec3, b: (number | vec3)?, c: number?, d: number?)
Add to the linear velocity of an entity. Same call shapes as
setVelocity.
Parameters
astring | entityRef | number | vec3— dx, a{x, y, z}delta vector, or the target (explicit): the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.b(number | vec3)(optional) — dy, dx, or the delta vector depending on call form.cnumber(optional) — dz or dy depending on call form.dnumber(optional) — Optional dz when targeting an explicit entity.
Physics.addVelocity(0, 5, 0)
Physics.addVelocity(entityId, 0, 5, 0)
Physics.addVelocity(entityId, {x=0, y=5, z=0})
globals/physics/addWheelCollider
physics.addWheelCollider(entityId: string | entityRef, config: table?)
Add a WheelCollider to an entity. The entity must be a child (or descendant) of a rigid body — the system walks up the hierarchy to find the Physics component. Every wheel under one body is a wheel of that body's ray-cast vehicle.
Parameters
entityIdstring | entityRef— Target entity id.configtable(optional) — Optional wheel configuration (radius?,suspensionDistance?,springRate?,damperRate?,targetPosition?,maxSuspensionForce?,bumpStopRecovery?,bumpStopSpeed?,groundAngle?,motorTorque?,maxDriveSpeed?,brakeTorque?,steerAngle?,forwardFriction?,sidewaysFriction?,frictionSlip?,sideFrictionStiffness?,corneringStiffness?,forwardFrictionStiffness?,slideGrip?,slideSlip?,loadSensitivity?,referenceLoad?,inertia?,rollingResistance?,width?,is2D?,visual?,solid?,mass?,breakLoad?,attached?). Asolidwheel is a volume other bodies strike; abreakLoadabove 0 lets it come off as a body of its own (Physics.detachWheeltakes it off on command). Aninertiaabove 0 makes the wheel spin on its own (wheelspin, lock-up, drift), andmaxDriveSpeed(m/s at the tread) is the fastest its drive spins it; the tyre grip curve fields shape its grip over slip and load (Physics.tyreCurvemeasures it,@builtin::modules.tyresholds presets).
Physics.addWheelCollider(id, { radius = 0.35, motorTorque = 500 })
globals/physics/advance
physics.advance(asked: number | PhysicsAdvanceOptions) -> PhysicsAdvance
Advance the physics simulation by exactly steps fixed steps (or the
simulated seconds the nearest whole number of steps covers), as fast as
the machine computes them, and return once the last one has run. This is
how to measure a physics outcome over many simulated seconds (an
acceleration run, a braking distance, a settle time, a lap, a bridge
under load, a replay of recorded inputs) in less wall time than the
seconds it covers, and how to run a fixed-step simulation exactly N steps
from a paused start and read the state after each (Physics.onAfterStep).
Every step is the step real-time play runs, at the same dt: 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 the step hooks and fixedUpdate reaches the state the same steps
reach at wall-clock rate; only the wall time differs. It runs from a paused
clock (engine.paused = true), which stays paused afterwards, or a running
one; while it runs the frame clock adds no steps of its own, and per-frame
code (update, task.wait, animation) keeps the frame clock, so drive a
measured run from the step hooks or fixedUpdate. Each frame runs as many
steps as fit in frameBudgetMs of wall time (default 100, 1 to 1000), so
the engine keeps drawing and answering while a long advance runs. It ends
with an error when the engine leaves the mode it started in. Run it in
play for a measurement, so leaving play puts the scene back. The call
waits: run it where code can yield (a tool call, a task), wrapping it in
task.spawn from a callback that cannot. One advance runs at a time.
Parameters
askednumber | PhysicsAdvanceOptions— A number of steps (1 to 1000000), or{ steps = n }/{ seconds = s }, either with an optionalframeBudgetMs.
Returns PhysicsAdvance — What ran: steps, firstStep, lastStep, simulatedSeconds, wallSeconds, steppingSeconds, frames, tickRate.
engine.paused = true; local ran = Physics.advance(180); print(ran.lastStep, entity(crate).position.y)
local ran = Physics.advance({ seconds = 10 }); print(`{ran.simulatedSeconds} s simulated in {ran.wallSeconds} s`)
globals/physics/airDensity
physics.airDensity(density: number?) -> number
The air's density, kg/m³: 1.225 by default (sea level, 15 °C). It
sets how hard the air drags on and lifts every body carrying
FluidForces or a LiftSurface. With density it sets it first:
thinner air high up or on another world, 0 for none.
Parameters
densitynumber(optional) — The density to set, 0 or more.
Returns number — The air's density now.
Physics.airDensity(0.02) -- the thin air of Mars
globals/physics/applyForce
physics.applyForce(entityIdOrForce: string | entityRef | vec3, force: vec3?, region: PhysicsSoftRegion?)
Apply a force to an entity's rigid or soft body, in newtons, for a
span of simulated time, whatever the frame rate and the physics tick rate
are. Called from code that runs inside a physics step
(Physics.onBeforeStep / onAfterStep, a contact listener, fixedUpdate)
it acts on the next physics step alone: call it once per step for a
continuous force.
Called anywhere else (update, a task, a tool call) it acts over the
simulated time the next frame advances, shared across however many steps
that frame runs: call it once per frame for a continuous force. Either
way a continuous force integrates to force times elapsed time, so a body
pushed up with its own weight floats. A force that depends on where the
body is or how fast it moves (a spring, a field, a controller) belongs in
Physics.onBeforeStep, which reads the state the step starts from; a
pull that drives an orbit or an oscillation keeps its energy given there
as the momentum it makes over the step, Physics.applyImpulse(id, force * dt).
With one argument the
script-context entity is targeted; with two args the explicit entity
id wins. A soft body takes the force spread over its particles by mass,
so it accelerates as a whole the way a rigid body of its mass would;
region puts it on part of the body instead ({ box = { min, max } }
or { nearest = point }, as Physics.softRegion takes it), which
accelerates that part alike and leaves the rest to follow.
Parameters
entityIdOrForcestring | entityRef | vec3— A force vector for the script-context entity, OR (paired withforce) the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.forcevec3(optional) — Optional force vector when targeting an explicit entity.regionPhysicsSoftRegion(optional) — Part of a soft body to push, asPhysics.softRegiontakes it; omit for the whole body.
Physics.applyForce({x=0, y=10, z=0})
Physics.applyForce(entityId, {x=0, y=10, z=0})
Physics.applyForce(cloth, {x=0, y=0, z=4}, { box = { min = {-0.5, -1, 0.4}, max = {0.5, 1, 0.5} } })
globals/physics/applyForceAtPoint
physics.applyForceAtPoint(entityId: string | entityRef, force: vec3, point: vec3, opts: PhysicsPushOptions?)
Apply a force at a specific world-space point, over the span
Physics.applyForce states: from Physics.onBeforeStep (or
fixedUpdate) on the next step alone, from anywhere else over the next
frame's simulated time. On a rigid body it generates the matching torque from the lever
arm. On a soft body it pushes the particles around the point, weighted
from the whole at the point to nothing at opts.radius (by default
twice the spacing of the body's particles), so the body gives way there
first. It always reaches at least the four particles nearest the point,
the smallest patch a body can dent, so a radius finer than the particles
are spaced spreads over that patch.
Parameters
entityIdstring | entityRef— The target: the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.forcevec3— Force vector, in newtons.pointvec3— World-space application point.optsPhysicsPushOptions(optional) —{ radius: number? }: how far into a soft body the force reaches, in metres.
Physics.applyForceAtPoint(id, {x=0,y=10,z=0}, {x=1,y=0,z=0})
Physics.applyForceAtPoint(jelly, {x=0,y=-40,z=0}, {x=0,y=1.5,z=0}, { radius = 0.3 })
globals/physics/applyImpulse
physics.applyImpulse(entityIdOrImpulse: string | entityRef | vec3, impulse: vec3?, region: PhysicsSoftRegion?)
Apply an instantaneous impulse (one-shot velocity change). With
one argument the script-context entity is targeted; with two args
the explicit entity id wins. A soft body takes the impulse spread over
its particles by mass, so it moves off as a whole the way a rigid body
of its mass would; region puts it on part of the body instead (as
Physics.softRegion takes it), which sets that part moving and leaves
the rest to follow. applyImpulseAtPoint aims one at a point.
Parameters
entityIdOrImpulsestring | entityRef | vec3— An impulse vector for the script-context entity, OR (withimpulse) the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.impulsevec3(optional) — Optional impulse vector when targeting an explicit entity.regionPhysicsSoftRegion(optional) — Part of a soft body to push, asPhysics.softRegiontakes it; omit for the whole body.
Physics.applyImpulse({x=0, y=5, z=0})
Physics.applyImpulse(entityId, {x=0, y=5, z=0})
Physics.applyImpulse(jelly, {x=0, y=-2, z=0}, { box = { min = {-0.5, 0.4, -0.5}, max = {0.5, 0.5, 0.5} } })
globals/physics/applyImpulseAtPoint
physics.applyImpulseAtPoint(entityId: string | entityRef, impulse: vec3, point: vec3, opts: PhysicsPushOptions?)
Apply an instantaneous impulse at a world-space point: a hit, a kick,
a crash. On a rigid body it changes the body's velocity and spin as an
impulse at that point of it would. On a soft body it pushes the particles
around the point, weighted from the whole at the point to nothing at
opts.radius (by default twice the spacing of the body's particles), so
the body dents there and the rest of it is carried along through its
elastic elements. It always reaches at least the four particles nearest
the point, the smallest patch a body can dent, so a radius finer than
the particles are spaced spreads over that patch; a finer dent takes a
finer body (a higher resolution). The impulse is the momentum the body
gains, in newton-seconds, wherever it lands.
Parameters
entityIdstring | entityRef— The target: the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.impulsevec3— The impulse, in newton-seconds.pointvec3— Where it lands, in world space: a contact point.optsPhysicsPushOptions(optional) —{ radius: number? }: how far into a soft body the impulse reaches, in metres.
Physics.applyImpulseAtPoint(crate, {x=0, y=0, z=-30}, hit.point)
local hit = Physics.raycast(muzzle, aim, 100); if hit then Physics.applyImpulseAtPoint(hit.body, {x=0, y=0, z=-30}, hit.point) end
local contact = Physics.contacts(shell)[1]; if contact then Physics.applyImpulseAtPoint(shell, {x=-60, y=0, z=0}, contact.points[1].point, { radius = 0.4 }) end
globals/physics/applyRadialImpulse
physics.applyRadialImpulse(entityId: string | entityRef, center: vec3, magnitude: number, opts: PhysicsPushOptions?)
Push a body straight away from a world point, like a blast: the
push is magnitude newton-seconds at the centre, weighted to nothing at
opts.radius (omitted, it reaches any distance at full strength). A
rigid body is pushed by the distance to its centre of mass; a soft body
particle by particle, each away from the centre by its own distance, so
a blast beside a balloon pushes it off and one inside a body spreads it
out. Each moves off at the speed magnitude gives a body of its mass.
Parameters
entityIdstring | entityRef— The target: the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.centervec3— The blast's world position.magnitudenumber— The impulse at the centre, in newton-seconds.optsPhysicsPushOptions(optional) —{ radius: number? }: how far the push reaches, in metres.
Physics.applyRadialImpulse(balloon, {x=0, y=1, z=-1}, 8, { radius = 3 })
for _, id in pile do Physics.applyRadialImpulse(id, blast, 20, { radius = 4 }) end
globals/physics/applyTorque
physics.applyTorque(entityIdOrTorque: string | entityRef | vec3, torque: vec3?)
Apply a torque to an entity's rigid body, over the span
Physics.applyForce states: from Physics.onBeforeStep (or
fixedUpdate) on the next step alone, from anywhere else over the next
frame's simulated time. With one argument
the script-context entity is targeted; with two args the explicit
entity id wins.
Parameters
entityIdOrTorquestring | entityRef | vec3— A torque vector for the script-context entity, OR (withtorque) the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.torquevec3(optional) — Optional torque vector when targeting an explicit entity.
Physics.applyTorque({x=0, y=1, z=0})
Physics.applyTorque(entityId, {x=0, y=1, z=0})
globals/physics/articulation
physics.articulation(entityId: string | entityRef) -> table?
The articulation a body is a link of: the tree of bodies its
articulated joints (articulated = true) join, solved in reduced
coordinates. Its links are listed root first, each parent before its
children.
Parameters
entityIdstring | entityRef— An entity whose body is a link, or its proxy.
Returns table? — { root, links, parents, linkDofs, dofs, rootFree }, or nil when the body is a link of no articulation: links holds each link's entity id, parents[i] the index in links of link i's parent (0 for the root), linkDofs[i] how many coordinates link i's joint leaves free (a hinge 1, a ball 3, the root 6 when it moves freely and 0 when it stands fixed), dofs their sum, root the root's entity id and rootFree whether it moves.
local a = Physics.articulation(hand); print(#a.links, a.dofs)
globals/physics/attachSoftRegion
physics.attachSoftRegion(softId: string | entityRef, targetId: string | entityRef, region: PhysicsSoftRegion?) -> number
Hold a region of a soft body to a rigid body, two-way: the region
follows the rigid body wherever it goes, and the rigid body carries the
region's weight and pull. Each particle in the region is tied to the
point of the rigid body it stands at when the attachment is made. The
attachment is an entry of the soft body's SoftBody component
(attachments), so it is saved with the scene, reaches every peer, and is
made again on a rebuilt body; it is released when either side is
removed. Its load reads back from Physics.softBodyState(softId).attachments.
A cloth's edge on a flagpole, a soft panel on a car's chassis, a jelly
glued to a moving platform. Where the rigid body's colliders touch the
soft body (a shell resting on its chassis), the contact and the hold push
on each other: keep them clear, or Physics.ignoreCollision(softId, targetId).
Parameters
softIdstring | entityRef— The soft body's entity (it carries aSoftBodycomponent).targetIdstring | entityRef— The rigid body's entity (it carriesPhysics), by id, name or proxy.regionPhysicsSoftRegion(optional) — Which particles to hold, asPhysics.softRegiontakes it:{ box = { min, max } },{ nearest = point }, withspace = "world"for world coordinates; nil holds the whole body.
Returns number — The attachment's index in the component's attachments.
Physics.attachSoftRegion(flag, pole, { box = { min = {-0.5, -1, -1}, max = {-0.45, 1, 1} } })
Physics.attachSoftRegion(shell, chassis, { box = { min = {-0.5, -0.5, -0.5}, max = {0.5, -0.4, 0.5} } })
globals/physics/attachWheel
physics.attachWheel(entityId: string | entityRef) -> boolean
Put a wheel that came off back on its vehicle, at its mount: its own body goes, and the vehicle drives on it again from the next physics tick.
Parameters
entityIdstring | entityRef— The wheel entity (it carries the WheelCollider).
Returns boolean — True when the entity carries a WheelCollider.
Physics.attachWheel(wheel.id)
globals/physics/bodyOf
physics.bodyOf(entityId: string | entityRef) -> PhysicsBodyOf?
The rigid body an entity stands for, or rides through the collider
authored on it: a ray or shape cast hit names the entity the collider was
authored on, and a collider on a child entity composes onto the nearest
ancestor's body, so this is the read that names the body to push, weigh
or follow. mass is the mass the solver holds, the one derived from the
colliders included, in kilograms.
Parameters
entityIdstring | entityRef— A body, or the entity a collider was authored on.
Returns PhysicsBodyOf? — A PhysicsBodyOf { entity, bodyType, mass }, or nil when the entity rides no rigid body (a world-space collider, an entity with none).
local hit = Physics.raycast(origin, dir, 20); local body = hit and Physics.bodyOf(hit.entityId)
local b = Physics.bodyOf(part); if b and b.bodyType == "dynamic" then Physics.applyImpulse(b.entity, { x = 0, y = 2 * b.mass, z = 0 }) end
globals/physics/bodyState
physics.bodyState(entityId: string | entityRef) -> PhysicsBodyState?
Everything the solver holds for one body — its type, mass, centre of
mass, inertia, gravity scale, damping, lock flags, CCD, collision groups,
sleep state, velocities, the force and torque queued for the next step,
its colliders and whether it collides at all (collides, with
collisionDetail naming why a body holding no collider meets nothing),
contacts, joints and transform constraints, and why it is not moving.
The entry Physics.observe(entityId) carries, read without
the world's accounting, so it costs what the one body costs.
Parameters
entityIdstring | entityRef— Entity id or proxy.
Returns PhysicsBodyState? — A PhysicsBodyState (with exists = false for an entity that carries no rigid body, and waitingFor naming what its collider needs while that collider cannot be built), or nil when nothing in the scene answers to that id.
local b = Physics.bodyState(id); print(b.bodyType, b.mass, b.stillness)
local b = Physics.bodyState(id); if not b.exists then print(b.waitingFor or "no body was built") end
local b = Physics.bodyState(id); if not b.collides then print(b.collisionDetail) end
globals/physics/boxCast
physics.boxCast(origin: vec3, halfExtents: vec3, direction: vec3, maxDistance: number?, exclude: (string | {string})?, options: PhysicsCastOptions?) -> PhysicsHit?
Cast a box along a direction and return the first hit.
A trigger (isTrigger) holds nothing up, so the sweep passes through it.
Many casts a frame: Physics.castMany answers them all in one call.
Parameters
originvec3— Box center at the start of the cast.halfExtentsvec3— Half the size of the box on each axis.directionvec3— Cast direction, of any length: the engine normalises it, somaxDistanceanddistanceare world units.maxDistancenumber(optional) — Optional distance limit.exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it.optionsPhysicsCastOptions(optional) — OptionalPhysicsCastOptions:{ mover = entity }casts for the entity the cast moves (a character controller, or anything moved by casts), so it meets colliders as that entity's body does: a one-way collider (oneWay) answers only on the face its direction points out of, to a cast that starts outside it; a collider whosecontactTagthe contact filter answers "ignore" or "sensor" with a tag of the mover's own colliders is passed; and the one-way collidersPhysics.passThrough(mover)drops the mover through are passed until it is clear of them.
Returns PhysicsHit? — Hit table { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }, or nil if nothing hit. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. surfaceVelocity is the collider's surfaceVelocity in world space (m/s), the motion its surface carries what stands on it with, and is absent for a collider whose surface holds still. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is.
local hit = Physics.boxCast(o, {x=0.5,y=0.5,z=0.5}, dir, 10)
local hit = Physics.boxCast(o, {x=0.5,y=0.5,z=0.5}, dir, 10, { selfId, carriedId })
globals/physics/capsuleCast
physics.capsuleCast(origin: vec3, radius: number, halfHeight: number, direction: vec3, maxDistance: number?, exclude: (string | {string})?, axis: vec3?, options: PhysicsCastOptions?) -> PhysicsHit?
Cast a capsule along a direction and return the first hit. The
capsule stands upright, or along axis: the up of a body standing on the
side of a planet (Physics.upAt).
This is the sweep that answers whether a body of that shape fits through
a passage: a capsule of radius r reports a hit on anything that leaves
it less than 2 * r of clearance.
A trigger (isTrigger) holds nothing up, so the sweep passes through it.
Many casts a frame: Physics.castMany answers them all in one call.
Parameters
originvec3— Capsule centre at the start of the cast.radiusnumber— Capsule radius.halfHeightnumber— Distance from the centre to either cap centre. The capsule standshalfHeight + radiustall in each direction.directionvec3— Cast direction, of any length: the engine normalises it, somaxDistanceanddistanceare world units.maxDistancenumber(optional) — Optional distance limit.exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it.axisvec3(optional) — Optional direction the capsule stands along, of any length (defaults to up,{ 0, 1, 0 }).optionsPhysicsCastOptions(optional) — OptionalPhysicsCastOptions:{ mover = entity }casts for the entity the cast moves (a character controller, or anything moved by casts), so it meets colliders as that entity's body does: a one-way collider (oneWay) answers only on the face its direction points out of, to a cast that starts outside it; a collider whosecontactTagthe contact filter answers "ignore" or "sensor" with a tag of the mover's own colliders is passed; and the one-way collidersPhysics.passThrough(mover)drops the mover through are passed until it is clear of them.
Returns PhysicsHit? — Hit table { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }, or nil if nothing hit. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. surfaceVelocity is the collider's surfaceVelocity in world space (m/s), the motion its surface carries what stands on it with, and is absent for a collider whose surface holds still. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is.
local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5)
local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5, selfId)
local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5, selfId, Physics.upAt(o))
local hit = Physics.capsuleCast(o, 0.3, 0.6, dir, 0.5, selfId, nil, { mover = selfId })
globals/physics/castMany
physics.castMany(queries: { PhysicsQuery }, results: { PhysicsQueryResult }?, options: { exclude: (string | { string })?, mover: (string | entityRef)? }?) -> { PhysicsQueryResult }
Answer many rays, shape casts and sphere overlaps in ONE call: the
call for a script that casts many queries a frame (the sight lines of a
crowd of guards, a flock's obstacle probes, the sub-steps of many
projectiles, a vehicle's ring of ground probes). Calling
Physics.raycast once per ray pays a crossing into the engine and a
fresh hit table every time; castMany pays one crossing for the whole
set and writes every answer into the results array, reusing the
tables of the array handed back in.
Each answer is the one the single call of its kind gives
(Physics.raycast, Physics.sphereCast, Physics.capsuleCast,
Physics.boxCast, Physics.overlapSphere), and answers from colliders
alone as they do.
Parameters
queries{ PhysicsQuery }— Array ofPhysicsQuerytables, answered in order:origin,direction(any length),maxDistance(default 1000),kind("ray", the default; "sphere" withradius; "capsule" withradius,halfHeightand optionalaxis; "box" withhalfExtents; "overlapSphere" withradius, its centre atorigin), and optionalexclude(an entity id or array of ids) andmover(asPhysicsCastOptions.mover). Keep the query tables and change their fields from frame to frame.results{ PhysicsQueryResult }(optional) — Optional array to write the answers into: pass the array the previous call returned and its tables are rewritten in place. Entries past the last query are removed. A new array when nil.options{ exclude: (string | { string })?, mover: (string | entityRef)? }(optional) — Optional{ exclude?, mover? }every query naming none of its own takes.
Returns { PhysicsQueryResult } — The results array: one PhysicsQueryResult per query, at the query's index. hit says whether it met anything; a hit carries entityId, point, normal, distance, startedInside, body, bodyType, and surface, surfaceVelocity and softBody as Physics.raycast reports them, with point, normal and surfaceVelocity as vector values; an overlap carries entityIds. A query that is not a table, misses a field its kind needs, or carries a value that is not a finite number is refused, naming its index and the field.
local results = Physics.castMany({ { origin = eye, direction = toPlayer, maxDistance = 30, exclude = guardId } })
-- every guard's sight line to the player in one call, the tables kept across frames
local queries, results = {}, {}
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 - eye.y, target.z - eye.z); q.maxDistance = 40; q.exclude = guard.id end
results = Physics.castMany(queries, results)
for i, r in results do guards[i].seesPlayer = r.hit and r.entityId == player.id end
local ground = Physics.castMany({ { kind = "sphere", radius = 0.3, origin = feet, direction = vector.create(0, -1, 0), maxDistance = 2 } })[1]
globals/physics/catchUp
physics.catchUp() -> PhysicsCatchUp
How the frame clock kept up with real time: the frames it ran, those
that dropped simulated time, and the simulated seconds they dropped,
which is time the world ran in slow motion. A frame drops time when it
owes more than it may catch up (boundSeconds, from
Physics.solverSettings().maxCatchUpSeconds), or when its steps past
maxSubsteps fall behind the time they cover (framesBehind: steps
that cost more than real time, which no frame rate catches up). The same
figures worldState().catchUp carries. Counted since the engine
started; the difference of two reads covers the frames between them,
which is how a game or an agent reads whether a tick rate keeps up on
the frames this engine draws. profiler.counters("physics.catch_up_*")
counts the same per frame: physics.catch_up_frames_at_bound,
physics.catch_up_frames_behind and physics.catch_up_dropped_us (the
microseconds dropped).
Returns PhysicsCatchUp — A PhysicsCatchUp.
local c = Physics.catchUp(); print(c.framesAtBound, c.framesBehind, c.droppedSeconds, c.boundSeconds)
local a = Physics.catchUp(); task.wait(2); local b = Physics.catchUp()
print("dropped", b.droppedSeconds - a.droppedSeconds, "s over", b.frames - a.frames, "frames")
globals/physics/colliderCount
physics.colliderCount() -> number
How many colliders the physics world holds. Zero means no ray, cast or overlap fired into this world can hit anything, so it is what separates a query that MISSED from a query fired into a world that holds nothing to hit. Read off the collider set itself, so it costs the same whatever the world holds.
Returns number — colliders across the whole physics world.
if Physics.colliderCount() == 0 then print("nothing here is solid") end
globals/physics/colliderGeometry
physics.colliderGeometry(options: table?) -> table?
Read the physics world as drawable triangles: every collider triangulated in world space into one indexed mesh, in GPU buffers ready to draw.
Box, sphere, capsule, cylinder, cone, convex, triangle-mesh and heightfield
colliders return their real surface, and a compound returns its children
folded together; a shape with no triangulation returns its bounding box and
reports exact = false.
options.colors is POSITIONAL over colliderManifest() — entry i colours
collider i — so you can colour by role, shape, entity or anything else you
read there. A position you leave out takes options.defaultColor.
The returned buffers are yours: destroy them when you replace them.
Parameters
optionstable(optional) —{ tessellation = "low"|"medium"|"high", colors = { {r,g,b,a}, ... }, defaultColor = {r,g,b,a} }.
Returns table? — { vertices, indices, vertexCount, indexCount, colliders } where each entry of colliders is { entity, colliderName?, shapeType, role, exact, firstIndex, indexCount }.
local geo = Physics.colliderGeometry({ tessellation = "high" })
globals/physics/colliderManifest
physics.colliderManifest() -> table
List every physics collider in the world with what it is and what it takes part in — no geometry, so it is the cheap read to make before deciding what to do with each one.
role is one of static, dynamic, kinematic, sensor. A sensor
is a collider the simulation holds as one, reported ahead of the body type
behind it, and a collider with no rigid body is static. exact says whether colliderGeometry would return this
collider's true surface or its bounding box.
Every collider of one entity shares its entity, so this is what to key
per-object decisions on. The order is stable across calls over an unchanged
world, which is what makes colliderGeometry's positional colours usable.
Returns table — Array of { entity, colliderName?, shapeType, role, exact }.
for _, c in ipairs(Physics.colliderManifest()) do print(c.entity, c.role) end
globals/physics/colliderOn
physics.colliderOn(entityId: string | entityRef) -> string?
Which collider component an entity carries, or nil when it carries none.
Parameters
entityIdstring | entityRef— Target entity id.
Returns string? The component name, e.g. "SphereCollider".
local which = Physics.colliderOn(id)
globals/physics/colliderShapes
physics.colliderShapes(entityId: string | entityRef) -> table
Read an entity's resolved physics collider shape(s) as the physics engine sees them, including auto-sized colliders.
shapeType is one of box, sphere, capsule, convex, mesh,
heightfield, compound, wire (a soft body's elements, colliding at
its particle radius), other: the shape the simulation is running, so
a mesh collider reads mesh.
params carries half-extents for a box, radius for a sphere, radius
and half-height for a capsule, and the collider's bounding half-extents
for the shapes that have no parametric description. A convex collider
reports its outline in linePoints instead.
Parameters
entityIdstring | entityRef— Target entity id.
Returns table — Array of resolved collider shapes (empty if none): { shapeType, position, rotation, params, linePoints, name? }.
local shapes = Physics.colliderShapes(id)
globals/physics/contactEvents
physics.contactEvents(target: (string | entityRef)?) -> { PhysicsContactEvent }
Every collision and contact event kept for target since the last call
for it, oldest first, each from its own physics step: begin, persist, end,
impact, trigger enter and exit, as Physics.listenContacts started keeping
them. Reading empties the list.
Parameters
target(string | entityRef)(optional) — The entitylistenContactsnamed, ornilfor every contact.
Returns { PhysicsContactEvent } — An array of PhysicsContactEvent, empty when nothing happened or nothing is kept for target.
for _, e in Physics.contactEvents(ball) do print(e.kind, e.other, e.step) end
globals/physics/contactEventsDropped
physics.contactEventsDropped() -> { engine: number, kept: number }
How many contact events the engine let go before anything read them:
its queue keeps 4096 between two deliveries, and each target listenContacts
keeps 1024. Zero when nothing was lost.
Returns { engine: number, kept: number } — { engine, kept }: dropped from the engine's queue, and from the lists listenContacts keeps, since the world started.
local lost = Physics.contactEventsDropped(); if lost.engine > 0 then log.warn("contact events dropped") end
globals/physics/contactFilters
physics.contactFilters(into: { PhysicsContactFilter }?) -> { PhysicsContactFilter }
Every entry of the world's contact filter (Physics.setContactFilter),
in tag order.
Parameters
into{ PhysicsContactFilter }(optional) — A table to write the entries into and return, the one an earlier read returned: each entry is written into the table at its index, so a script reading the filter every frame allocates nothing. A new table when left out.
Returns { PhysicsContactFilter }: { a, b, mode } each (into when given).
for _, f in Physics.contactFilters() do print(f.a, f.b, f.mode) end
globals/physics/contactPeak
physics.contactPeak(target: string | entityRef) -> PhysicsContactPeak?
The hardest hit target took since the last call for it: the largest
normal impulse one physics step put between it and anything it touched,
with who, on which step, how fast the two were closing as that step
began, and the surfaces each side is made of where the hit landed. Every
step counts, so an impact that began and ended between two reads is still
the peak it was. The engine keeps it while anything listens to target
(Physics.listenContacts, onContact, onImpact, onTrigger). Reading
starts the next peak afresh.
Parameters
targetstring | entityRef— A listened entity.
Returns PhysicsContactPeak? — A PhysicsContactPeak { other, impulse, closingSpeed, step, surface?, otherSurface? }, or nil when nothing pushed on it since the last read.
Physics.listenContacts(body); local peak = Physics.contactPeak(body); if peak then print(peak.impulse, peak.closingSpeed) end
globals/physics/contacts
physics.contacts(entityId: string | entityRef, otherId: (string | entityRef)?) -> { PhysicsContact }
Every contact one body's colliders are in right now, with the other
entity, the normal, how deeply the two interpenetrate, the normal and
friction impulse the last step applied, how fast the two were closing as
that step began, the step, and each contact point: the read behind "is it
touching", "is it grounded" and "how hard did that hit land". It describes
the last physics step; to detect every collision, hit and impact as an
event on the step it happens, use Physics.onContact, Physics.onImpact
or Physics.contactPeak. A pair is listed while its
surfaces touch: a pair kept apart (Physics.ignoreCollision, collision
groups) or no longer touching is not. For a soft body these are the
contacts of its surface with every other collider, another soft body's
surface included. A contact with a soft body on either side names the
particles of it that are touching (particles for this side,
otherParticles for the other), so a hit can be answered where it
landed. Name otherId to read only the contacts with that one entity:
a body resting on the ground holds a contact point per surface element
that touches it, and a read of one pair costs that pair alone.
Parameters
entityIdstring | entityRef— Entity id or proxy.otherId(string | entityRef)(optional) — Optional entity id or proxy: report only the contacts with it.
Returns { PhysicsContact } — An array of PhysicsContact — empty when the body touches nothing, or when the entity carries neither a rigid body nor a soft body.
for _, c in Physics.contacts(id) do print(c.other, c.deepestPenetration) end
for _, c in Physics.contacts(truck, pole) do if c.totalImpulse > 5 then print("dented at", #c.particles, "particles") end end
globals/physics/cutSoftBody
physics.cutSoftBody(softId: string | entityRef, blade: { vec3 } | { point: vec3, normal: vec3 })
Cut a soft body along a blade, every element of the body the blade
meets opening along it: { point = p, normal = n } cuts along the whole
plane through p facing n, splitting the body in two wherever it lies on
both sides; { a, b, c } cuts along that world-space triangle, which cuts
only as far as the triangle reaches. Applied straight after the next physics
step; a piece the cut separates becomes an entity of its own (see
onSoftBodyTear), and the cut reports as a tear of kind "cut". A plane is
measured against the body where that step leaves it, so it cuts a moving
body wherever it has gone; a cut that opens nothing is reported in the log.
Raises when the entity carries no SoftBody, and in edit mode, where
nothing simulates.
Parameters
softIdstring | entityRef— The soft body's entity.blade{ vec3 } | { point: vec3, normal: vec3 }—{ point = vec3, normal = vec3 }for a plane, or the triangle's three world-space corners{ a, b, c }.
Physics.cutSoftBody(jelly, { point = vector.create(0, 1, 0), normal = vector.create(1, 0, 0) }) -- in two along x = 0
Physics.cutSoftBody(jelly, { vector.create(0, -5, -5), vector.create(0, 5, -5), vector.create(0, 0, 10) })
-- slice off the part of a body 0.2 m above its centre
local c = Physics.softBodyState(jelly).centerOfMass
Physics.cutSoftBody(jelly, { point = vector.create(c.x, c.y + 0.2, c.z), normal = vector.create(0, 1, 0) })
globals/physics/debugLines
physics.debugLines(opts: table?) -> (PhysicsDebugLines?, string?)
Draw what the physics world simulates beyond collider surfaces as
world-space lines, with what each object's lines picture as data. This is
the read the physics debug views draw from: capture { pass = "physics" }
and the edit-mode collider overlay (debugViz category colliders) both
show these lines.
Layers:
cage draws a soft body's elements coloured by load: slack blue, yellow
half way, red at the load it tears (see PhysicsSoftBodyDiagnostics for
how a load is read);
particles draws its particles: free ones as small grey crosses, pinned
ones as green octahedra, ones held to a rigid body as magenta octahedra;
contacts draws the contacts soft surfaces hold against soft surfaces
(their own included): the segment joining the two witness points in
orange, the normal in cyan;
wheels draws each WheelCollider wheel: its suspension ray as far as
it reaches, its whole travel and the tyre's radius below the mount (green
on ground, red in the air, as the wheel's isGrounded reads), the travel
from its mount to the tyre's centre coloured by how much of it is taken
up on the same ramp, its tyre circle in white across its steered axle,
and its ground point (yellow) and normal (cyan).
Answers in edit mode as well as play mode; in edit mode a vehicle stands
at rest with its wheels where they are authored.
Parameters
optstable(optional) —{ layers: {string}?, entities: {(string | entityRef)}? }:layersnames the layers to draw (every layer when omitted; an unknown name is an error naming the layers),entitieskeeps to those entities' objects (a wheel is kept by its own entity or its chassis').
Returns (PhysicsDebugLines?, string?) — A PhysicsDebugLines, or nil and the reason on a VM that holds no physics world (a worker).
local d = Physics.debugLines(); print(d.lineCount, #d.objects)
for _, o in Physics.debugLines({ layers = { "particles" } }).objects do print(o.entity, o.pinned, o.attached) end
local w = Physics.debugLines({ layers = { "wheels" }, entities = { truck } }); for _, o in w.objects do print(o.index, o.grounded, o.compression) end
globals/physics/defineSurface
physics.defineSurface(name: string, surface: PhysicsSurfaceDefinition?)
Define a surface: a named material of contact coefficients that a
collider takes by naming it in its surface field (every collider
component carries one), and that a heightfield takes per sample through
surfaceLayers / surfaceMap (how each painted layer of a terrain is its
own ground). A surface holds friction, restitution,
rollingResistance (a body rolling on it loses speed at this many times
gravity on level ground, so a ball rolled at v stops after
v^2 / (2 * rollingResistance * 9.81)), spinningResistance (the same for
a body spinning on it about the contact normal) and free tags (what a
footstep, a skid mark or an impact sound reads it by). Per contact the
two sides' friction and restitution average and their resistances add
(a ball of none on a floor of c rolls against c). Contacts, contact
events and ray and shape cast hits name the surface each side is made of
at the point, and Physics.groundContact names what a body stands on.
Defining a name again replaces it, and every collider naming it takes the
new values from the next physics step; a collider naming a surface no one
defined keeps its own coefficients and still reports the name.
Parameters
namestring— The surface's name, 1 to 64 bytes.surfacePhysicsSurfaceDefinition(optional) —{ friction?, restitution?, rollingResistance?, spinningResistance?, tags? }; unstated coefficients take friction 0.5 and 0 for the rest.
Physics.defineSurface("gravel", { friction = 0.6, rollingResistance = 0.04, tags = { "loose", "crunchy" } })
Physics.defineSurface("ice", { friction = 0.05, rollingResistance = 0.002 })
entity("road").component.add("BoxCollider", { half = { 50, 0.5, 4 }, surface = "gravel" })
globals/physics/defineWater
physics.defineWater(name: string, body: PhysicsWaterDefinition)
Define a body of water, which Physics.water then answers from at any
point and moment: physics, scripts and AI all read water through it.
body.kind is what the water is:
"flat": still water atlevel. Within aregionwhose min Y is finite, that is its floor: a pool, a tank, a flooded room (leveldefaults to the region's max Y)."waves": a sea over the stilllevel, the sum of the waves it lists (waves = { { amplitude, wavelength, direction, phase?, steepness?, omega? } }: heightamplitude * cos(k (d . p) - omega t + phase), the surface point moved sideways bysteepness * amplitudealong the directiond({x, z}or an angle from +X),omegadefaulting to deep water'ssqrt(9.81 k)) and of thelatticesof a spectrum's waves it carries (what a sea of the Tidewater water kit defines); its time is the water clock wrapped toperiodand scaled byspeed; over agroundgrid its waves shoal away to nothing at the waterline acrossshoalDepthmetres."grid": a landscape's lakes and rivers, a level per texel over the rectangle atorigin({x, z}) ofsize({x, z}) metres,columnsxrowstexels, dry where a texel carries no level. Its water runs down the slope of its own surface at Manning's speed over a bed ofroughness(default 0.035), so a level lake stands still and a river runs along its channel, unlessflowstates it per texel (finite at every wet texel).levels,ground.heightsandflowtake a list of numbers or the texels of a float texture ({ texels, channels = 4, channel = 1, wet = 2 }).
Every kind takes region, a current the whole body carries (m/s),
priority (where bodies overlap the higher answers, then the higher
surface; defaults waves 0, grid 1, flat 2), density (kg/m³, default
1000 for fresh water; 1025 for the sea), which a body carrying
FluidForces floats against and is dragged by, and entity, which the
body goes with. space says which coordinates the body is stated in:
"world" (the default) or "entity", the local space of its entity:
every position, level, size, region and current it states is then that
entity's, and the body stands, turns, tilts and scales wherever the
entity does, following it as it moves, the way the entity's own
colliders do, and covers no point while the entity is scaled to nothing
along an axis. A Terrain's water is stated in the landscape's own
coordinates this way. A Terrain with water and a sea of the Tidewater
water kit define theirs, a Water component places still water in a box
saved with its scene, and content defines a pool, a tank or a river of its
own. Defining a name again replaces the body; a body that cannot be
sampled is refused with the reason.
Parameters
namestring— The body's name, 1 to 128 bytes.bodyPhysicsWaterDefinition— The body, as above.
Physics.defineWater("pool", { kind = "flat", region = { min = { x = -5, y = 0, z = -5 }, max = { x = 5, y = 2, z = 5 } } })
Physics.defineWater("pond", { kind = "waves", level = 1, waves = { { amplitude = 0.1, wavelength = 6, direction = { x = 1, z = 0.3 } } } })
Physics.defineWater("canal", { kind = "flat", level = 0, region = { min = { x = 0, y = -3, z = -4 }, max = { x = 200, y = 0, z = 4 } }, current = { x = 1.5, y = 0, z = 0 } })
Physics.defineWater("deck pool", { kind = "flat", level = 1, region = { min = { x = -2, y = 0, z = -3 }, max = { x = 2, y = 1, z = 3 } }, entity = ship, space = "entity" })
globals/physics/defineWind
physics.defineWind(name: string, wind: PhysicsWindDefinition)
Define a wind field: air moving through the world, which pushes on
every body carrying FluidForces (a soft body's triangles included) or a
LiftSurface inside each physics step, and which Physics.wind answers
with the same value so a flag, a tree or a particle system bends with
what the bodies feel. Every field covering a point adds to the wind
there. kind says what it blows at each point:
"steady" (the default) blows velocity (m/s) everywhere it reaches.
"grid" reads velocities between the centres of the texels around a
point, over the box at origin of size metres cut into columns
along X, rows along Z and layers along Y (default 1: a map, the same
at every height of its box): air around a building, a valley channelling
it, a storm front painted over a map. velocities lists x, y, z per
texel, along X first, then Z, then Y, or takes a float texture's texels,
{ texels = string | buffer of little-endian f32, channels = 4, x = 1, y = 2, z = 3 }, each axis naming the channel it reads (an axis named by
none reads 0). scroll (m/s) moves the pattern through its box on the
water clock, wrapping around it; wrap = true repeats the grid past its
box, where otherwise it blows nothing outside it.
"vortex" turns the air about axis (default up) through center, like
a solid body inside the core of radius metres and slowing as
radius / distance outside it; speed (m/s) is its speed at the core's
edge, by the right-hand rule about axis, so the core turns at
speed / radius rad/s; inflow (m/s) draws the air in toward the axis
and updraft (m/s) lifts it along the axis, from its full speed on the
axis to nothing at updraftRadius metres out (default radius: the
core alone; wider, a column that carries up what the vortex swings
around outside its core): a tornado, a dust devil, a whirlpool's air.
"radial" blows out of center at speed (m/s, negative draws it in) at
radius metres, rising from nothing at the centre and slowing past
radius by the square of the distance, or, with an axis, out across
that line and slowing by the distance: a blast, a rotor's downwash.
Every kind adds velocity on top. gust (m/s) is how far the speed at
a point rises and falls along the wind there over gustPeriod seconds
(default 4); gusts travel downwind at the wind's speed and differ across
it over gustSize metres (default 20); where a field blows nothing it
gusts along gustDirection. region ({ min, max }) keeps the field to
a box it reaches full strength falloff metres inside of: a fan, an
updraft, a wind tunnel, a gap between buildings. entity ties it to an
entity it goes with; with space = "entity" every position, size,
direction, region and velocity it states is in that entity's local
space, and the field stands, turns and scales wherever the entity does,
following it as it moves. Gusts and scrolling follow the water clock
(Physics.waterTime), so a step feels the wind of its own moment.
Defining a name again replaces the field; one that cannot be sampled is refused with the
reason. The Wind component places a wind as an entity saved with its
scene, a steady, grid, vortex or radial one.
Parameters
namestring— The field's name, 1 to 128 bytes.windPhysicsWindDefinition— The field, as above.
Physics.defineWind("breeze", { velocity = { x = 6, y = 0, z = 1 }, gust = 3 })
Physics.defineWind("updraft", { velocity = { x = 0, y = 9, z = 0 }, region = { min = { x = -3, y = 0, z = -3 }, max = { x = 3, y = 30, z = 3 } }, falloff = 1 })
Physics.defineWind("tornado", { kind = "vortex", center = { x = 40, y = 0, z = 0 }, radius = 6, speed = 30, inflow = 4, updraft = 12, updraftRadius = 15, region = { min = { x = 0, y = -5, z = -40 }, max = { x = 80, y = 60, z = 40 } }, falloff = 10 })
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 } })
Physics.defineWind("downwash", { kind = "radial", entity = heli, space = "entity", center = { x = 0, y = -1, z = 0 }, axis = { x = 0, y = 1, z = 0 }, radius = 3, speed = 12, velocity = { x = 0, y = -10, z = 0 }, region = { min = { x = -12, y = -20, z = -12 }, max = { x = 12, y = 0, z = 12 } } })
globals/physics/detachSoftRegion
physics.detachSoftRegion(softId: string | entityRef, targetId: (string | entityRef)?) -> number
Release regions of a soft body held with attachSoftRegion (or
authored in its SoftBody component's attachments).
Parameters
softIdstring | entityRef— The soft body's entity.targetId(string | entityRef)(optional) — Release only the regions held to this rigid body; omit to release every one.
Returns number — How many attachments were released.
Physics.detachSoftRegion(flag, pole)
Physics.detachSoftRegion(shell)
globals/physics/detachWheel
physics.detachWheel(entityId: string | entityRef) -> boolean
Take a wheel off its vehicle: it leaves as a dynamic body of its own
from where it stands, moving as it moved and spinning as it spun, with
its mass and with the wheel entity's own collider as its collider,
which leaves the chassis with it (a cylinder of its radius and width
for a wheel holding none or whose own collider is a trigger, which then
rides the wheel's body beside it), and the vehicle drives on the wheels
it has left. The wheel entity stays under the chassis in the hierarchy;
Physics.getVelocity, applyImpulse and the contact listeners reach
it as any body. A wheel also comes off by
itself when its reaction passes its breakLoad. On a shared world
the peer that may write the wheel takes it off for every peer.
Parameters
entityIdstring | entityRef— The wheel entity (it carries the WheelCollider).
Returns boolean — True when the entity carries a WheelCollider.
Physics.detachWheel(wheel.id); print(Physics.getWheelState(wheel.id).detachReason) -- "command"
globals/physics/digestLog
physics.digestLog(opts: table?) -> PhysicsDigestLog
Read the digests the recording kept, oldest first: digests[i] is
the state digest at the end of step steps[i].
Parameters
optstable(optional) —{ from?, to?, frames? }:from/tobound the steps read (inclusive);frames = trueaddsframes, each step's recordedPhysicsStateDigestwith itsentries.
Returns PhysicsDigestLog — A PhysicsDigestLog. dropped counts the steps that fell out of the recording's bounds.
local log = Physics.digestLog(); print(#log.digests, log.digests[#log.digests])
globals/physics/drawnPose
physics.drawnPose(entityId: string | entityRef, into: { [string]: any }?) -> PhysicsDrawnPose?
Where an entity is drawn this frame, and where its transform puts
it. The simulation advances in fixed ticks (physics.tick_rate, 60 a
second by default) while frames are drawn at the display's rate, so a
body with Physics.interpolation on is drawn blended between its last two
ticks, and everything parented under it is drawn moved with it.
entity.position reports the drawn pose from a component's update, a
task or a tool call, and the simulated pose, which moves only when a tick
runs, from code inside a step (step hooks, contact listeners,
fixedUpdate); this read reports both, wherever it is made. Its
simulatedPosition is the pose the last tick left.
Parameters
entityIdstring | entityRef— Entity id or proxy. Any entity answers; one the simulation does not blend is drawn at its simulated pose.into{ [string]: any }(optional) — A table to write the pose into and return, the one an earlier read returned: its position and rotation tables are written in place and a field the pose leaves out is cleared, so a script reading this every frame into one table allocates nothing. A new table when left out.
Returns PhysicsDrawnPose? — A PhysicsDrawnPose (into when given), or nil when nothing in the scene answers to that id.
local d = Physics.drawnPose(car); print(d.position.z, d.simulatedPosition.z, d.interpolated)
local d = Physics.drawnPose(tyre); print(d.interpolated, d.interpolatedBy)
local held = {}; local d = Physics.drawnPose(lift, held)
globals/physics/driveSoftElements
physics.driveSoftElements(softId: string | entityRef, targets: { [number]: number }, opts: { speed: number? }?)
Drive the length of authored elements of a custom soft body: each
named element's rest length moves toward its target at opts.speed
(metres per second; 0 or omitted sets it at once), pushing and pulling
with no more than the element's own maxForce, so a blocked ram stalls
instead of tearing the body. A hydraulic ram, a muscle, a crane's luffing
cylinder. The drive holds until the element's fields are written again
(an element of kind "actuator" is driven to its targetLength from its
fields). Takes effect from the next physics step, on the peer that
simulates the body.
Parameters
softIdstring | entityRef— The soft body's entity.targets{ [number]: number }— Element number (as listed in the component'selements) to the length in metres it is driven to.opts{ speed: number? }(optional) —{ speed: number? }: how fast the lengths move, in metres per second.
Physics.driveSoftElements(crane, { [7] = 2.5, [8] = 2.5 }, { speed = 0.4 })
globals/physics/firstDivergence
physics.firstDivergence(a: table, b: table) -> PhysicsDivergence?
Find where two simulations first part. Pass two Physics.stateDigest
results, or two Physics.digestLog results (read with frames = true to
name more than the step). Logs are compared step by step from their first
recorded step, over the steps both hold, so two engines that started
recording at the same point of the same scripted run line up whatever
their own step numbers. The answer names the first index and step whose
digests differ, then the first body, joint or soft body (in hash order)
whose own digest differs, then, when values were recorded, the first
field and component that differs, with both values. Values compare as
their bits, or under the digest's quantum when one was set.
Parameters
atable— The first engine's digest or log.btable— The second engine's digest or log, taken with the same options.
Returns PhysicsDivergence? — nil when they agree; otherwise a PhysicsDivergence: reason is "digest" (only the digests were kept), "missing" (an entry one side lacks: missingIn names the side), "entry" (the entry's digest differs, no values kept), "field" (field, component, axis, particle for a soft body, and the values a / b) or "count" (a soft body's particle counts differ). index is the log position, step / stepB each side's step number. The first entry in hash order is often a body whose state moved by the last bit only because the cause pushed it, so largest names the value that differs the most at that step across every entry with values: { kind, key, field, component, axis, particle, a, b, delta }.
local d = Physics.firstDivergence(logA, logB); if d then print(d.step, d.key, d.field, d.axis, d.a, d.b) end
globals/physics/fluidForces
physics.fluidForces(entityId: string | entityRef) -> PhysicsFluidForces?
What the air and the water put on a body on the last physics step:
its FluidForces (buoyancy, drag, Magnus) and its LiftSurfaces (each
surface's lift, drag, angle of attack and stall), worked out from the
pose and velocity the body started that step at. Nil for a body neither
acts on, or one no step has worked them out for yet (a paused world).
For a soft body, the totals over its surface.
Parameters
entityIdstring | entityRef— Entity id or proxy of a rigid or soft body.
Returns PhysicsFluidForces?.
local f = Physics.fluidForces(crate); print(f.submerged, f.buoyancy.y)
for _, s in Physics.fluidForces(car).surfaces do print(s.name, s.lift.y, s.stalled) end
globals/physics/forces
physics.forces(entityId: string | entityRef) -> PhysicsBodyForces?
Which forces act on a body from step to step, and their sum: every
Force component driving it (on its entity or an entity under it, each
named by its source entity and instance name), each evaluated at the
pose the body stands at now, in the world frame, as the next step
applies it. applied reads whether this engine's step applies them: an
enabled dynamic body takes them, a static or kinematic one carries them
unmoved. Forces written for one step (applyForce) are the body state's
queuedForce.
Parameters
entityIdstring | entityRef— Entity id or proxy of a body.
Returns PhysicsBodyForces? — A PhysicsBodyForces (force, torque, forces, applied), with empty forces and zero sums for a body carrying none, or nil when nothing in the scene answers to that id with a rigid body.
local f = Physics.forces(rocket); print(f.force.y, #f.forces)
globals/physics/getAngularVelocity
physics.getAngularVelocity(entityId: (string | entityRef)?, into: { [string]: any }?) -> vec3?
Read the angular velocity of an entity's rigid body.
Parameters
entityId(string | entityRef)(optional) — Target entity id or proxy; resolves from script context when omitted.into{ [string]: any }(optional) — A table to write the angular velocity'sx,yandzinto and return: a script reading this every frame into one table allocates nothing. A new table when left out.
Returns vec3? — Angular velocity in rad/s (into when given), or nil if the entity has no rigid body.
local w = Physics.getAngularVelocity(id)
local held = {}; local w = Physics.getAngularVelocity(id, held)
globals/physics/getGravity
physics.getGravity() -> vec3
Read the current world gravity vector.
Returns vec3 — Gravity vector in m/s² (negative y is "down" in the default world).
local g = Physics.getGravity()
globals/physics/getSurface
physics.getSurface(name: string) -> PhysicsSurface?
The surface name names, as Physics.defineSurface defined it.
Parameters
namestring— The surface's name.
Returns PhysicsSurface?: nil when no surface of that name is defined.
local s = Physics.getSurface(hit.surface); if s and table.find(s.tags, "loose") then sprayGravel(hit.point) end
globals/physics/getVelocity
physics.getVelocity(entityId: (string | entityRef)?, into: { [string]: any }?) -> vec3?
Read the linear velocity of an entity's rigid body, or of its soft body as a whole (its particles' velocities averaged by mass).
Parameters
entityId(string | entityRef)(optional) — Target entity id or proxy; resolves from script context when omitted.into{ [string]: any }(optional) — A table to write the velocity'sx,yandzinto and return: a script reading this every frame into one table allocates nothing. A new table when left out.
Returns vec3? — Velocity in m/s (into when given), or nil if the entity has no rigid body.
local v = Physics.getVelocity(id)
local held = {}; local v = Physics.getVelocity(id, held)
globals/physics/getWheelState
physics.getWheelState(entityId: string | entityRef) -> PhysicsWheelState?
Read a wheel collider's runtime state. Reads the native component the wheel system writes after each physics step.
Parameters
entityIdstring | entityRef— Target entity id (must carry a WheelCollider component).
Returns PhysicsWheelState? — PhysicsWheelState: { entityId, isGrounded, compression, angularVelocity, rotation, skid, slipRatio, slipAngle, roadSpeed, load, peakSlipRatio, peakSlipAngle, sideGrip, sideImpulse, forwardImpulse, sideForce, forwardForce, suspensionForce, stopImpulse, center, hitPoint, hitNormal, surface?, ground?, solid, reaction, breakLoad, attached, detachReason?, detachLoad, vehicleOrder }, or nil if the component is absent. surface is the surface the tyre touches (Physics.defineSurface; the painted layer under it on a terrain), absent on ground naming none, and ground the entity id of what it touches, absent in the air. A tyre grips a defined surface with its stated grip times the surface's friction, and the surface's rollingResistance adds to the tyre's own. reaction is the force (N) the ground and whatever struck the wheel's volume put on it in the last tick, what breakLoad is measured against; attached is true while the wheel stands on its vehicle (false from the moment it is asked off or comes off, and true again once the physics tick after Physics.attachWheel has put it back on its mount), detachReason says why it came off ("load" or "command") and detachLoad the reaction it came off at; vehicleOrder is the wheel's place among its vehicle's wheels, from 1, the order the vehicle steps them in and Physics.vehicleState lists them in (a wheel that came off keeps the place it last held, and one that has not stepped on a vehicle reads 0). compression runs from 0 at the spring's rest up to suspensionDistance, where the bump stop is; angularVelocity is the wheel's spin (rad/s) and rotation its angle about its axle in radians, both growing as it rolls forward; skid is how fast the tyre slides (m/s) while its grip is used up, 0 while it holds (sideways only, unless the wheel spins on its own); slipRatio is the tread's speed less the road's under it, both positive rolling forward, as a share of the road speed, signed the way the tyre pushes the car (rolling forward: 0 rolling, positive in wheelspin, -1 locked; rolling backward the signs turn over; 0 for a wheel with no inertia, which rolls at the road speed); slipAngle is the angle in degrees between the line the tyre rolls along and the way its contact moves, positive toward the wheel's right (the drift angle at the tyre); roadSpeed is the ground's speed under the tyre along that line (m/s); load is the force the tyre presses the ground with (N); peakSlipRatio and peakSlipAngle (degrees) are the slip ratio and the slip angle its grip peaks at along the road and across it on the ground it touches, whatever its load (0 for a tyre that grips with nothing that way, and peakSlipRatio 0 for a wheel with no inertia), the peaks Physics.tyreCurve sweeps to, and sideGrip the share of its peak grip across the road it pushed across it with at the slip ratio and slip angle it ran at, at the load it carried (its grip along the road and its slide past its peak both counted; at most 1, and 1 for a tyre that grips with nothing across the road); the impulses are what the tyre applied to the chassis this tick (N·s) and the forces the same over the tick (N), and stopImpulse what the bump stop applied once the suspension was used up; center is the wheel centre in world space.
local state = Physics.getWheelState(id)
globals/physics/gravityAt
physics.gravityAt(point: vec3, groups: number?, into: { [string]: any }?) -> vec3
The gravity at a point: the acceleration the physics step gives a
dynamic body standing there (gravity scale 1). Planet gravity, a pull
toward an axis or a surface, or a zone pulling its own way come from the
GravityField components acting there; elsewhere it is the world's
gravity vector. It is exactly what the step applies, so a character
controller, a follow camera, an AI or a vehicle takes its down from it.
Parameters
pointvec3— The point, in world space.groupsnumber(optional) — The collision membership of the body asking, as a bitmask; a field acts on a body whose membership shares a bit with itsgroups. Default: every group.into{ [string]: any }(optional) — A table to write the answer'sx,yandzinto and return: a script reading this every frame into one table allocates nothing. A new table when left out.
Returns vec3 — The gravity there, in m/s² (into when given).
local g = Physics.gravityAt(entity(ship).position)
local mass = 2; Physics.applyForce(ship, { -g.x * mass, -g.y * mass, -g.z * mass }) -- hover against any planet
local held = {}; local g = Physics.gravityAt(vector.create(x, y, z), nil, held)
globals/physics/gravityFieldsAt
physics.gravityFieldsAt(point: vec3, groups: number?, into: { [string]: any }?) -> PhysicsGravityFieldsAt
Which gravity fields act at a point and what each gives there: the read that tells why a body falls the way it does near several planets, an inverted sphere or a zone.
Parameters
pointvec3— The point, in world space.groupsnumber(optional) — The collision membership of the body asking, as a bitmask. Default: every group.into{ [string]: any }(optional) — A table to write the answer into and return, the one an earlier read returned: itsgravity, itsfieldsand each entry of them are written in place, so a script reading this every frame into one table allocates nothing. A new table when left out.
Returns PhysicsGravityFieldsAt — A PhysicsGravityFieldsAt: gravity (as Physics.gravityAt), fromFields, and fields, each { entityId, shape, acceleration, counted } (into when given).
for _, f in Physics.gravityFieldsAt({ 0, 12, 0 }).fields do print(f.entityId, f.shape, f.counted) end
local held = {}; local here = Physics.gravityFieldsAt(vector.create(x, y, z), nil, held)
globals/physics/groundContact
physics.groundContact(entityId: string | entityRef, maxSlope: number?) -> PhysicsGroundContact?
What a body stands on now: of its contacts whose normal leans less
than maxSlope degrees from straight up against gravity, the one the
last step pushed hardest, with the surface it is made of under the body.
The read a footstep sound, a tyre without a WheelCollider, a skid mark
or dust takes to know what is underfoot, on a painted terrain as well.
Parameters
entityIdstring | entityRef— Entity id or proxy carrying a rigid body.maxSlopenumber(optional) — Optional steepest ground counted, in degrees from level (default 60).
Returns PhysicsGroundContact?: nil when nothing holds the body up.
local g = Physics.groundContact(player); if g and g.surface == "gravel" then playStep("gravel") end
globals/physics/hasLineOfSight
physics.hasLineOfSight(fromId: string | entityRef, toId: string | entityRef) -> boolean
Check whether two entities have line-of-sight between their
origins: a ray from the viewer's world position to the target's meets
no collider but the target's own. The colliders of the body each end
rides (its own body, or the body of its nearest ancestor carrying one)
and of every entity riding that body belong to that end, so neither the
viewer's own colliders nor the target's hold the sight line up.
Many viewers checked every frame (a crowd of guards): Physics.castMany
answers every sight line in one call, each query a ray from a viewer
toward the target that excludes the viewer, seeing it where entityId
is the target's.
Parameters
fromIdstring | entityRef— Viewer entity, an id or a proxy.toIdstring | entityRef— Target entity, an id or a proxy.
Returns boolean — true when no collider sits between them (including coincident origins), false otherwise. Raises naming the argument when fromId or toId names no entity.
if Physics.hasLineOfSight(a, b) then ... end
globals/physics/ignoreCollision
physics.ignoreCollision(entityIdA: string | entityRef, entityIdB: string | entityRef, ignore: boolean?)
Keep two entities from colliding, or let them collide again. Covers
every collider each one owns (its rigid body with the shapes composed
onto it, its standalone collider, its ragdoll's bones, its soft body's
surface), so it keeps a soft shell off the chassis it is held to as well
as two rigid bodies apart. An ignored pair holds no contact: the solver
pushes neither one and Physics.contacts lists neither to the other.
It applies from the next physics step, to bodies already touching as
well, and lasts until it is turned off, either entity is despawned, or
the mode changes: entering or leaving play starts without it, so make
the call where the bodies are set up for play (a component's onLoad).
It stands beside collision groups: a pair either one excludes does not
collide. A vehicle's WheelColliders stand only where its chassis
collides, so the wheels of a chassis in an ignored pair pass the other
entity as the chassis does.
Parameters
entityIdAstring | entityRef— First entity id.entityIdBstring | entityRef— Second entity id.ignoreboolean(optional) — Whentrue(default) the pair is kept apart;falselets it collide again.
Physics.ignoreCollision(a, b, true)
globals/physics/immersion
physics.immersion(target: string | entityRef) -> PhysicsImmersion?
How much of an entity stands in the water: the share of it under the
surface, the water it displaces, how deep its centre and its lowest point
stand, which body of water it is in and whether it is in the water by the
rule Physics.onWater raises entries and exits by. Works for any body
(with or without FluidForces), a character, a collider or an entity's
origin, in any water: a pool, a Water component, an ocean, a terrain's
lakes and rivers. For an entity Physics.onWater watches it is what the
last physics step measured; for any other it is measured now. Use it for
how wet something is, a swim depth, a boat's draft, a sinking timer.
Parameters
targetstring | entityRef— The entity.
Returns PhysicsImmersion? — A PhysicsImmersion { inWater, submerged, submergedVolume, volume, wetArea, depth?, deepest?, water?, surfacePoint?, center, velocity, step }, or nil when the entity has nothing to measure.
local w = Physics.immersion(boat); if w and w.submerged > 0.9 then print("sinking") end
local w = Physics.immersion(player); local wading = w ~= nil and (w.depth or -1) > -0.5
globals/physics/isSleeping
physics.isSleeping(entityId: (string | entityRef)?) -> boolean?
Whether an entity's rigid or soft body is currently asleep (at rest and not simulating). A body sleeps once it stops moving, to save simulation cost.
Parameters
entityId(string | entityRef)(optional) — Target entity id or proxy; resolves from script context when omitted.
Returns boolean? — true if asleep, false if awake, or nil if the entity has neither a rigid nor a soft body.
if Physics.isSleeping(id) then Physics.wakeUp(id) end
globals/physics/jointBreaks
physics.jointBreaks() -> table
Every joint that has broken since the last call to this function.
A joint breaks when the reaction it carries exceeds the breakForce
(newtons of force on the body carrying it) or breakTorque (newton-metres
of moment about its anchor) its joint was given; each joint
reports once and its constraint is already released when the record
arrives. The 256 most recent are kept: a structure that comes apart while
nothing reads them drops the oldest beyond that, as the engine's own queue
does beyond 1024.
Returns table — Array of { entityId, joint, jointEntityId, connectedEntityId, kind, impulse, angularImpulse, force, torque, position }, oldest first: entityId is the entity whose Joint broke and joint that Joint's name (nil for its unnamed Joint), so one of a body's several joints is named; jointEntityId is the entity carrying its constraint.
for _, e in ipairs(Physics.jointBreaks()) do print(e.entityId, e.force) end
globals/physics/jointReaction
physics.jointReaction(entityId: string | entityRef | table, name: string?) -> PhysicsJointReaction?
The load (the stress) an entity's joint is carrying right now, as the
constraint solver resolved it on the last physics step: the force and the
moment it applies to the body carrying it, as vectors and read along the
member it holds, so tension tells from compression, axial load from shear
and bending from twist. This is the same quantity a break threshold is
measured against, and load is the share of breakForce / breakTorque
it stands at. A joint with a soft body at either end reads the same way.
Physics.jointReactions reads many joints in one call.
Parameters
entityIdstring | entityRef | table— Entity carrying the Joint component, or aJointcomponent.namestring(optional) — The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.
Returns PhysicsJointReaction? — A PhysicsJointReaction, or nil when the entity owns no joint or its constraint is not built yet. axial is the force along the member at this body's end, positive pulling it outward (tension) and negative pushing it inward (compression): a member hanging 10 kg reads +98.1, one propping it -98.1. direction is that line, from the body's centre of mass out to its anchor; connectedAxial reads the connected body as a member the same way. tension is the pull along the line between the two anchors (a rope's or a spring's), 0 while they stand together. shear is the force across the member, bending the moment across it, torsion the moment about it. worldForce / worldTorque are the force and the moment about the anchor the joint applies to this body (N, N·m), localForce / localTorque the same along the joint frame's axes, and force / torque their sizes. load is the larger of force / breakForce and torque / breakTorque, 1 breaking the joint, 0 with no threshold. A joint Physics.listenJointLoads listens to carries peak, the largest load any step put on it since the last read, which reading takes.
local r = Physics.jointReaction(id); print(r and r.axial)
local r = Physics.jointReaction(beam, "right"); if r and r.axial < 0 then print("compressed", -r.axial) end
globals/physics/jointReactions
physics.jointReactions(targets: any?, opts: { vectors: boolean?, fields: { string }? }?) -> PhysicsJointReactions
The load (the stress) of many joints in one call, as arrays of one
value per joint, each read the way Physics.jointReaction reads one: a
whole bridge or machine coloured by load in one read a frame. targets is
an array of Joint components and entities (each entity's unnamed Joint),
in the order the arrays answer; one entity, for every joint its body is in;
or nil for every joint in the world. Each joint is named by entityId
(whose Joint), joint (its name, empty for the unnamed one),
jointEntityId and connectedEntityId, and by bodyEntityId and
connectedBodyEntityId, the entities of the two bodies it holds: the
members to sum a structure's loads on. A joint Physics.listenJointLoads listens to gives
the peak it carried since its last read in peakLoad, peakMaxAxial and
peakMinAxial, which reading takes; every other joint gives its current
reading there.
Parameters
targetsany(optional) — An array of Joints and entities, one entity, or nil for every joint.opts{ vectors: boolean?, fields: { string }? }(optional) —{ fields = { "axial", "load" } }builds only the arrays it names (any listed in the return, the vectors and names included), the cheapest read of a large structure;{ vectors = true }adds the arraysworldForce,worldTorque,localForce,localTorque,directionandpositionof {x, y, z}. Reading the same joints every frame, pass theirjoint:jointEntityId()ids, taken once, in place of the Joints.
Returns PhysicsJointReactions — A PhysicsJointReactions: count, and the arrays exists (false while a joint's constraint is not built, its values 0), axial, connectedAxial, tension, shear, bending, torsion, force, torque, impulse, load, listened, peakLoad, peakMaxAxial, peakMinAxial.
local r = Physics.jointReactions(); for i = 1, r.count do print(r.entityId[i], r.axial[i], r.load[i]) end
local r = Physics.jointReactions(members); for i = 1, r.count do if r.load[i] > 0.8 then print(i, "near breaking") end end
local r = Physics.jointReactions(ids, { fields = { "axial", "load" } }); print(r.axial[1], r.load[1])
globals/physics/jointState
physics.jointState(entityId: string | entityRef | table, name: string?) -> table?
Where an entity's joint stands as of the last physics step: the angle
of a hinge, the travel of a prismatic, the swing and twist of a ball
joint, whether it is at a limit, and the force its limit and motor
applied. axes holds the same for each axis of the joint's frame (the
frame's X along the joint's axis). Angles are degrees, angular
velocities radians per second, travels metres.
Parameters
entityIdstring | entityRef | table— Entity carrying the Joint component, or aJointcomponent.namestring(optional) — The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.
Returns table? — { kind, angle?, offset?, swing?, twist?, velocity?, atLimit, limitForce, motorForce, distance, length?, slipping, axes }, or nil while the entity owns no built joint. A rail adds where its point stands on its path: progress (metres from the path's start), speed (m/s along it, positive toward its end), length, closed, laps (times round a loop, signed), onPath (false once it ran off an open end, left naming which), atEnd ("start" / "end" while a capped end holds it), offset (metres off the path), railMotorForce / frictionForce (newtons along the path, signed), tangent, normal (toward the bend's centre) and curvature (1/m). angle (hinge, degrees) or offset (prismatic, metres) with its velocity; swing / twist (ball, degrees); atLimit is true while any limit holds the joint at a bound or pushes on it; limitForce / motorForce are the largest force or torque a limit / the motor applied; distance is metres between the anchors; length (rope) is the rope's length as it stands, its maxDistance grown by whatever it paid out at its yieldForce; slipping is true when the joint gave way at its yieldForce / yieldTorque over the last step; axes.<linX..angZ> = { position, velocity, locked, limited, min, max, atLimit, limitForce, motorized, motorForce } with angles in degrees. articulated is true for a link of an articulation, whose limitForce and motorForce (and each axis') are nil: its limits and motors act on its coordinates, and their forces are not measured.
local s = Physics.jointState(door); print(s.angle, s.atLimit)
if Physics.jointState(elbow).atLimit then playSound("creak") end
globals/physics/listenContacts
physics.listenContacts(target: (string | entityRef)?, opts: PhysicsContactOptions?) -> () -> ()
Start keeping an entity's collision and contact events for polling:
from now on every event of the kinds opts names is kept for
Physics.contactEvents(target) to read, and the hardest hit it takes for
Physics.contactPeak(target), however many physics steps run between two
reads. Keeps the most recent 1024 events per target. Calling it again for
the same target replaces the options. The events stop being kept when the
returned function runs, or when the component that called it is removed
or its entity destroyed.
Parameters
target(string | entityRef)(optional) — The entity whose events to keep, ornilfor every contact in the world.optsPhysicsContactOptions(optional) —PhysicsContactOptions, asonContacttakes it.
Returns () -> () — A function that stops keeping them and drops what was kept.
local stop = Physics.listenContacts(body, { minImpulse = 100 })
for _, e in Physics.contactEvents(body) do if e.kind == "impact" then print(e.other, e.impulse) end end
globals/physics/listenJointLoads
physics.listenJointLoads(targets: any?, listen: boolean?)
Keep the peak load of joints between reads: from the next physics
step on, every step offers its load to each joint's peak, and
Physics.jointReaction(..).peak and the peak* arrays of
Physics.jointReactions take it, so a load that crossed a threshold for
one step and fell back is still read however many steps ran between two
reads. Only listened joints (and breakable ones) are measured every step.
Listening ends when listen is false or the joint's entity is gone.
Parameters
targetsany(optional) — AJoint, an entity (every joint its body is in), or an array of Joints and entities.listenboolean(optional) — True (the default) to keep the peak, false to stop.
Physics.listenJointLoads(bridgeJoints)
local r = Physics.jointReaction(cable); if r and r.peak and r.peak.load > 1 then print("overloaded at step", r.peak.step) end
globals/physics/loadReplay
physics.loadReplay(data: string) -> PhysicsReplayInfo
Take a recording Physics.saveReplay wrote in place of the one held,
stopping a recording that runs and ending the replay; play it with
Physics.playReplay. It names its entities by id, so it plays over the
scene it was recorded in.
Parameters
datastring— The stringPhysics.saveReplayreturned.
Returns PhysicsReplayInfo — A PhysicsReplayInfo.
local data = vfs.read("/source/replays/crash.replay"); if data then Physics.loadReplay(data); Physics.playReplay({ rate = 0.5 }) end
globals/physics/loadSnapshot
physics.loadSnapshot(source: string | buffer) -> PhysicsSnapshot
Read back a snapshot snapshot:save(path) wrote, or the bytes
snapshot:bytes() gave, on this engine or another one (native or
browser) holding the same bodies. The bytes are a versioned
little-endian format, the same on every platform. Returns a snapshot
Physics.restore takes.
Parameters
sourcestring | buffer— A VFS path the snapshot was saved to, or its bytes as a buffer.
Returns PhysicsSnapshot — The snapshot.
local s = Physics.loadSnapshot("/zero/source/saves/bridge.physics"); Physics.restore(s)
globals/physics/measureSoftBody
physics.measureSoftBody(softId: string | entityRef, test: { [string]: any }) -> PhysicsSoftMeasurement?
Measure how a soft body responds to a stated load, without building a
rig: a copy of it, built from its component as authored, is pressed
between two plates, sent at a speed into a post or a wall, or dropped onto
a floor, in a world of its own at the tick and solver iterations the
world's settings state (in edit mode as in play), and every step is sampled: force against displacement, its
energy and what it absorbed. The live body is untouched. A press answers
its initial stiffness (N/m), peakForce, the work under the loading
curve and the permanentSet; an impact the crush, peakForce,
peakDeceleration, rebound and the share of its energy it absorbed
(absorbedShare); a drop the same against the height. Tune a material
toward "takes X kJ over Y m" with it, then build the body.
Parameters
softIdstring | entityRef— The soft body's entity.test{ [string]: any }— One load:{ press = { depth, axis?, speed?, hold?, settle?, friction? } }(axis "x", "y" or "z" in the body's own frame, default "y"; speed default depth / 2 s; frictionless plates unlessfrictionsays otherwise),{ impact = { speed, direction?, radius?, offset?, carried?, duration?, friction? } }(direction default "-z", a post ofradiusmetres or a wall when it is left out,carriedkilograms on a rigid block held to its trailing face) or{ drop = { height, duration?, friction? } }.
Returns PhysicsSoftMeasurement? — A PhysicsSoftMeasurement, or nil when nothing in the scene answers to that id. Its stability is the measured copy's stability report at the rate the test ran, so a body added in the same call reads one too. A test the body cannot run (a field out of range, a press deeper than the body, a mesh body whose model has not been filled yet) raises an error naming why. A body added in the same call is measured as its component builds it at the entity's pose and scale.
local m = Physics.measureSoftBody(block, { press = { depth = 0.05 } }); print(m.stiffness, m.work, m.absorbed)
local m = Physics.measureSoftBody(nose, { impact = { speed = 15, radius = 0.1, carried = 700 } }); print(m.crush, m.rebound, m.absorbedShare, m.peakDeceleration / 9.81)
local m = Physics.measureSoftBody(crate, { drop = { height = 2 } }); print(m.absorbed, m.elastic, m.dissipated, m.gravityWork)
globals/physics/motionPeak
physics.motionPeak(target: string | entityRef, name: string?) -> PhysicsMotionSample?
The sample with the largest g-force (proper acceleration) a motion
probe took since the last call for it: the hardest moment of a crash, a
hit or a turn. Every sample counts, whether or not Physics.motionSamples
read it. Reading starts the next peak afresh.
Parameters
targetstring | entityRef— The probed entity.namestring(optional) — The probe's name, whenPhysics.probeMotiongave it one.
Returns PhysicsMotionSample? — A PhysicsMotionSample, or nil when the probe took nothing since the last read or no probe has that target and name.
local peak = Physics.motionPeak(car, "seat"); if peak and peak.g > 20 then print("severe impact", peak.g) end
globals/physics/motionProbe
physics.motionProbe(target: string | entityRef, name: string?) -> PhysicsMotionProbeInfo?
What a motion probe is doing: the rate it samples at (samples per second), the length of its latest sample, how many samples the latest physics step took, how many it keeps and how many wait to be read, how many it let go since it was placed, and whether it is bound to a body (with the reason when it is not: no entity carries the id, or the entity holds no body the probe can measure).
Parameters
targetstring | entityRef— The probed entity.namestring(optional) — The probe's name, whenPhysics.probeMotiongave it one.
Returns PhysicsMotionProbeInfo? — A PhysicsMotionProbeInfo, or nil when no probe has that target and name.
local info = Physics.motionProbe(car, "seat"); print(info.rate, "samples/s", info.dropped, "dropped")
globals/physics/motionSamples
physics.motionSamples(target: string | entityRef, name: string?) -> { PhysicsMotionSample }
Every sample a motion probe took since the last call for it, oldest
first, each from the solver substep (or physics step) it was taken in,
however many steps ran between two calls: read it once a frame, or from
fixedUpdate, and nothing is missed. A sample carries the point's
velocity, acceleration, proper acceleration (what is felt), g-force,
angular velocity and angular acceleration, and its step, time and length.
Reading empties the list. Physics.motionProbe states the rate the
samples are taken at and how many were let go.
Parameters
targetstring | entityRef— The probed entity.namestring(optional) — The probe's name, whenPhysics.probeMotiongave it one.
Returns { PhysicsMotionSample } — An array of PhysicsMotionSample, empty when the probe took none since the last read or no probe has that target and name.
for _, s in Physics.motionSamples(car, "seat") do if s.g > 4 then print("hard hit", s.g, s.step) end end
local samples = Physics.motionSamples(ball); local last = samples[#samples]; if last then print(last.acceleration, last.g) end
globals/physics/observe
physics.observe(entityId: (string | entityRef)?, opts: table?) -> PhysicsObservation?
Read the solver's own state — the world's accounting, and what it
holds for each body plus why it is not moving one. Every value comes off
the simulation rather than the Physics component, so a write the solver
refused or clamped reads back as what it kept. Answers in edit mode as
well as play mode.
Parameters
entityId(string | entityRef)(optional) — Report on this one entity. Omit for every body in the world.optstable(optional) —{ bodies: boolean?, contactPoints: boolean? }—bodies = falsebuilds the world accounting alone, andcontactPoints = falsekeeps each contact pair's normal, depth, impulse and point count while leaving out the individual points. Both default to true.
Returns PhysicsObservation? — A PhysicsObservation, or nil when entityId names nothing in the scene. bodies is an array, not a table keyed by entity id — each entry names its own entity in entity.
local o = Physics.observe(); for _, b in o.bodies do print(b.entity, b.stillness) end
local o = Physics.observe(id); print(o.bodies[1].stillness, o.bodies[1].stillnessDetail)
globals/physics/onAfterStep
physics.onAfterStep(fn: (number, number) -> ()) -> () -> ()
Call fn at the end of every physics step from now on, at the
physics tick rate, however many steps a frame runs. It runs once the step
has integrated, after that step's collision events reached their
listeners (Physics.onContact, onImpact, onTrigger) and before
fixedUpdate, so a read here sees what this step left: positions,
velocities, Physics.jointReaction, Physics.contactPeak. Use it to
sample a trajectory step by step, measure energy, record a replay, or
react to a step's result. A force written here acts on the next step. One
engine call runs every hook. The hook ends the way an onBeforeStep hook
ends, and must not wait either.
Parameters
fn(number, number) -> ()— Receives(dt, step): the step's length in seconds and its number.
Returns () -> () — A function that removes this hook.
local samples = {}; local off = Physics.onAfterStep(function(dt, step) table.insert(samples, entity(ball).position.y) end)
globals/physics/onBeforeStep
physics.onBeforeStep(fn: (number, number) -> ()) -> () -> ()
Call fn at the start of every physics step from now on, at the
physics tick rate (physics.tick_rate), however many steps a frame runs.
It runs after the step's force reset and before the step integrates, so a
force, torque, impulse or velocity written here acts on this very step,
and a read here (a position, a velocity, a raycast) sees the state the
step starts from. This is the place for a force that depends on where a
body is or how fast it moves: gravity toward a planet, a spring, a
thruster holding altitude, buoyancy, a PID controller, an active
ragdoll's balance. applyForce holds a force over the whole step the
way gravity is held; a pull that stands in for gravity (an orbit) or
drives an oscillation keeps its energy when it is given as the momentum
it makes over the step instead: Physics.applyImpulse(id, force * dt).
One engine call runs every hook, so one hook looping
over many bodies costs about what the loop costs. Runs while the gameplay
clock runs, on every engine that steps the world: under multiplayer push
only the bodies this peer simulates. The hook ends when the returned
function is called, or when the component that registered it is removed,
its entity destroyed or its code reloaded. A hook must not wait
(task.wait); spawn a task from it for work that does. The engine runs
the hooks of the engine thread's VM, so a worker job's call (a
jobs.dispatch entry) raises, naming the refusal.
Parameters
fn(number, number) -> ()— Receives(dt, step): the step's length in seconds and its number, thestepthe contact events of this step carry.
Returns () -> () — A function that removes this hook.
local off = Physics.onBeforeStep(function(dt) Physics.applyForce(ship, { 0, 9.81 * 500, 0 }) end)
Physics.onBeforeStep(function(dt) local p = entity(moon).position; local r = math.sqrt(p.x * p.x + p.y * p.y + p.z * p.z); local k = -GM * mass * dt / (r * r * r); Physics.applyImpulse(moon, { p.x * k, p.y * k, p.z * k }) end)
globals/physics/onContact
physics.onContact(target: (string | entityRef)?, fn: (PhysicsContactEvent) -> (), opts: PhysicsContactOptions?) -> () -> ()
Call fn for each collision and contact event of an entity's colliders
from now on: on collision begin, while the two stay in contact, on
collision end, on an impact (a hit, by how hard it lands), and on a
trigger's enter and exit. Events are recorded by the physics step itself
and fn runs once per step, before that step's fixedUpdate, so an
impact that lasts one step is heard even when a frame runs several steps.
The listener ends when the returned function is called, or when the
component that registered it is removed or its entity destroyed. Only the
colliders somebody listens to cost the step anything. Use it to detect a
hit, a landing, two things touching or parting, or a body in a zone.
Parameters
target(string | entityRef)(optional) — The entity whose contacts to hear: a body (every collider it is built from), a collider's own entity, a trigger, a soft body.nilhears every contact in the world.fn(PhysicsContactEvent) -> ()— Receives onePhysicsContactEventper event, seen fromtarget:{ kind, step, entity, other, collider, otherCollider, removed, otherRemoved, trigger, normal, closingSpeed, impulse, tangentImpulse, peakImpulse, totalImpulse, steps, pointCount, points }. The "end" a destroyed entity causes names it by the id it went by, withotherRemovedtrue.optsPhysicsContactOptions(optional) —PhysicsContactOptions:{ kinds?, minImpulse?, minSpeed? }.kindsdefaults to begin, end, enter and exit, plus impact whenminImpulseis given; add "persist" for an event on every step of a contact.
Returns () -> () — A function that removes this listener.
local off = Physics.onContact(ball, function(e) if e.kind == "begin" then print("hit", e.other, e.closingSpeed) end end)
Physics.onContact(nil, function(e) print(e.kind, e.entity, e.other) end, { kinds = { "begin", "end" } })
Physics.onContact(public.entityId, function(e) log.info(`{e.kind} with {e.other}`) end)
globals/physics/onImpact
physics.onImpact(target: (string | entityRef)?, fn: (PhysicsContactEvent) -> (), opts: PhysicsContactOptions?) -> () -> ()
Call fn for every impact (a collision hit) on an entity from now on:
the physics step on which the normal impulse between it and something it
touches rises past minImpulse newton-seconds. Each impact is heard once,
on the step it lands, with the impulse of that step (impulse, N s; a
rigid stop of mass m from speed v is m * v), how fast the two were closing
as they met (closingSpeed, m/s) and where (points); the impulse divided
by the step's time is the mean impact force over it. Use it to detect a hit
and answer it: damage, impact sounds, fall damage, scoring, breaking things.
Runs once per physics step, before that step's fixedUpdate.
Parameters
target(string | entityRef)(optional) — The entity to hear impacts on, ornilfor every impact in the world.fn(PhysicsContactEvent) -> ()— Receives onePhysicsContactEvent(kind "impact") per impact.optsPhysicsContactOptions(optional) —{ minImpulse?, minSpeed? }: the impulse an impact must reach (default 0, the step a pair first takes any load) and the closing speed it must reach.
Returns () -> () — A function that removes this listener.
Physics.onImpact(box, function(e) print("hit by", e.other, e.impulse, "N s at", e.closingSpeed, "m/s") end, { minImpulse = 50 })
Physics.onImpact(player, function(e) if e.closingSpeed > 12 then takeFallDamage(e.closingSpeed) end end)
globals/physics/onJointBreak
physics.onJointBreak(fn: (table) -> ()) -> () -> ()
Call fn for every joint that breaks from now on, with the same record
jointBreaks returns.
Parameters
fn(table) -> ()— Receives one break record per broken joint.
Returns () -> () — A function that removes this listener.
local off = Physics.onJointBreak(function(e) print(e.kind, e.force, e.position) end)
globals/physics/onLatch
physics.onLatch(target: (string | entityRef)?, fn: (PhysicsLatchEvent) -> ()) -> () -> ()
Call fn each time two Latch points latch from now on: a hitch takes
its coupler, two train cars couple, a ship docks, a door catches. A step
latches two points that accept each other's tags when they come within
reach turned within their maxAngle and closing no faster than their
maxSpeed, and joins them with the joint the Latch states. fn runs once
per latch, on the peer that simulates both bodies, after the step that
made it and before its fixedUpdate, with the joint already made.
Parameters
target(string | entityRef)(optional) — The entity whose Latch point to hear, seen from it;nilhears every latch in the world once, seen from its host.fn(PhysicsLatchEvent) -> ()— Receives{ kind = "latch", latch, other, host, joint, position, distance, angle, speed, step }:latchthe point heard andotherthe one it latched to,hostthe point whose entity carries the joint,jointthatJoint(every joint read takes it),positionmidway between the points,distancemetres andangledegrees apart,speedm/s they closed at.
Returns () -> () — A function that removes this listener.
local off = Physics.onLatch(trailer, function(e) print("hitched to", e.other, e.distance) end)
Physics.onLatch(nil, function(e) print(e.latch, "latched", e.other, "at", e.speed, "m/s") end)
globals/physics/onSoftBodyTear
physics.onSoftBodyTear(fn: (PhysicsSoftBodyTear) -> ()) -> () -> ()
Call fn for every tear of a soft body from now on: a body loaded past
its tearStrain or tearForce (fields of its SoftBody component), cut
by Physics.cutSoftBody or torn by Physics.tearSoftBody. The torn entity
keeps the largest piece; every piece split off is an entity of its own by
the time fn runs, standing at the root of the scene and carrying a
SoftBody with the torn body's fields, its share of the model and the
material, the velocity, dents and pins that fell on its side. Its body
joins it on the next frame, and an impulse applied to it in fn reaches
the body then. A piece is play state: it is left out of every save, and
leaving play takes it away and gives the torn entity back its whole body.
Parameters
fn(PhysicsSoftBodyTear) -> ()— Receives onePhysicsSoftBodyTearper tear:{ entity, pieces, position, kind, particles }.
Returns () -> () — A function that removes this listener.
local off = Physics.onSoftBodyTear(function(e) print(e.entity, #e.pieces, e.position) end)
Physics.onSoftBodyTear(function(e) for _, id in e.pieces do Physics.applyImpulse(id, { x = 0, y = 2, z = 0 }) end end)
globals/physics/onTrigger
physics.onTrigger(target: (string | entityRef)?, fn: (PhysicsContactEvent) -> ()) -> () -> ()
Call fn when a body enters or leaves a trigger from now on (on
trigger enter, on trigger exit). A trigger is a collider with isTrigger
set: it holds nothing up and reports what overlaps it, whether it stands
alone or rides a body, and it detects dynamic and kinematic bodies alike.
A fixed trigger leaves out the fixed geometry it stands in, such as the
floor under a zone. An entity with no body of its own is heard by the
volume stated for it (Physics.setWaterVolume), standing where its
transform puts it: a CharacterController states its capsule, so the
player walking into a zone or over a pickup enters and leaves it.
Parameters
target(string | entityRef)(optional) — The trigger's entity, or the entity whose trigger overlaps to hear;nilhears every trigger in the world.fn(PhysicsContactEvent) -> ()— Receives onePhysicsContactEventper enter ("enter") and exit ("exit"), seen fromtarget, withotherthe entity that entered or left. An entity destroyed inside the trigger leaves it with an "exit" naming the id it went by,otherRemovedtrue.
Returns () -> () — A function that removes this listener.
Physics.onTrigger(zone, function(e) if e.kind == "enter" then print(e.other, "entered") end end)
Physics.onTrigger(coin, function(e) if e.kind == "enter" and e.other == layers.active.players.localPlayer.avatar.id then print("collected") end end)
globals/physics/onUnlatch
physics.onUnlatch(target: (string | entityRef)?, fn: (PhysicsLatchEvent) -> ()) -> () -> ()
Call fn each time two latched Latch points come apart from now on:
released (Physics.releaseLatch, a Latch's :release(), or the latch's
Joint taken off with Physics.removeJoint), broken (the latch joint's
breakForce / breakTorque exceeded), or removed (a point or its entity
went away). A freed point latches again once it has stood
clear of every point it latches to.
Parameters
target(string | entityRef)(optional) — The entity whose Latch point to hear, seen from it;nilhears every unlatch once.fn(PhysicsLatchEvent) -> ()— Receives{ kind = "unlatch", latch, other, reason, force?, torque?, position? }:reasonis "release", "break" (with the break'sforceN,torqueN m andposition), "removed", or "refused" (the latch's joint could not be made:errornames why).
Returns () -> () — A function that removes this listener.
Physics.onUnlatch(door, function(e) if e.reason == "break" then print("burst open at", e.force, "N") end end)
globals/physics/onWater
physics.onWater(target: (string | entityRef)?, fn: (PhysicsWaterEvent) -> (), opts: { kinds: { string }? }?) -> () -> ()
Call fn each time an entity goes into or comes out of the water from
now on: any body of water Physics.defineWater defined, a Water
component, an ocean, a terrain's lakes and rivers. A body, a character, a
thrown object or a projectile goes in ("enter") on the physics step 1% or
more of it stands under the surface, and comes out ("exit") on the step
no part of it does, so a body floating or bobbing at the surface stays in
until it leaves the water whole and raises nothing while it bobs. An
entity destroyed while in the water, or one no listener watches any more,
comes out on that step, at the surface it stood in, so every entry is
followed by one exit (a count of what is in the pool stays right). The
event carries where it crossed the surface, how fast (normalSpeed, the
speed into the water along the surface normal at the moment it met the
surface: a ball dropped from 5 m enters at 9.9 m/s) and which water. The
step measures it however fast it moves, and fn runs once per step,
before that step's fixedUpdate. Use it for splashes and splash sounds,
wet footsteps, a swim state, a fish taking a bait, a boat taking on
water, scoring a dive, a water hazard. The listener ends when the
returned function is called, or when the component that registered it is
removed or its entity destroyed. An entity is measured by the volume
Physics.setWaterVolume states (a CharacterController states its
capsule), else its rigid body, else its own collider, else its origin.
Physics.immersion reads how much of it is under at any time.
Parameters
target(string | entityRef)(optional) — The entity to watch, ornilfor every dynamic and kinematic body and every character in the world.fn(PhysicsWaterEvent) -> ()— Receives onePhysicsWaterEventper entry or exit:{ kind, step, entity, water, point, normal, normalSpeed, velocity, submerged, depth }.opts{ kinds: { string }? }(optional) —{ kinds? }: the kinds to hear, default both "enter" and "exit".
Returns () -> () — A function that removes this listener.
Physics.onWater(ball, function(e) if e.kind == "enter" then print("splash at", e.point, e.normalSpeed, "m/s") end end)
Physics.onWater(nil, function(e) log.info(`{e.entity} {e.kind} {e.water}`) end)
local off = Physics.onWater(player, function(e) swimming = e.kind == "enter" end)
globals/physics/orbitVelocity
physics.orbitVelocity(point: vec3, centre: vec3, axis: vec3?, groups: number?) -> vec3
The velocity that carries a body on a circular orbit through point
about centre, under the gravity at point (Physics.gravityAt): the
speed sqrt(pull * r) from the pull toward centre there and the
distance r to it, across the radius and axis (the orbit's own axis,
default +Y, the orbit then lying level). Set it on a moon, a satellite or
a slingshot projectile and a GravityField toward centre keeps it
going round. Errors when nothing pulls toward centre at point, or
when axis runs along the radius. A GravityField added this frame
stands in the physics world from the next step, so an orbit set up in
the same script as its planet is started from Physics.onBeforeStep.
Parameters
pointvec3— Where the orbit passes, in world space.centrevec3— What it goes round: the field's centre (a planet's position).axisvec3(optional) — The axis the orbit turns about. Default: +Y.groupsnumber(optional) — The collision membership of the orbiting body, as a bitmask. Default: every group.
Returns vec3 — The velocity, in m/s.
local v = Physics.orbitVelocity(entity(moon).position, entity(planet).position); Physics.setVelocity(moon, v)
globals/physics/overlapSphere
physics.overlapSphere(center: vec3, radius: number) -> { string }
Find every entity id whose colliders overlap a sphere.
A trigger (isTrigger) holds nothing up, so it is left out.
Many overlaps a frame: Physics.castMany answers them all in one call.
Parameters
centervec3— Sphere center in world space.radiusnumber— Sphere radius.
Returns { string } — Array of overlapping entity ids: a collider on a body is named by the entity standing for that body, once however many of its colliders overlap, and a collider with no body (static world geometry such as the ground) by its own entity. Each id is what the push verbs take.
local ids = Physics.overlapSphere({x=0,y=0,z=0}, 5)
globals/physics/passThrough
physics.passThrough(entityId: string | entityRef, throughId: (string | entityRef)?)
Let a rigid body standing on one-way colliders drop through them (a
platformer's "down + jump"). A collider is one-way when its oneWay
field names the direction bodies pass through it along; on the next
physics step every one-way collider the body touches, or with throughId
only those that entity owns, stops holding it, and the body falls
through until it is clear. A one-way collider it reaches afterwards
holds it as before. Wakes the body. The entity's rigid body (a Physics
component, or a ragdoll's bones) is what drops. An entity with no rigid
body is a mover the engine moves by casts (a CharacterController):
every cast made for it (options.mover of Physics.raycast and the
shape casts) passes the one-way colliders it stands on (its own collider,
or its origin, within 0.1 m of them or inside them) until it is clear of
each, so it falls through them under its own gravity.
Parameters
entityIdstring | entityRef— The body that drops through: entity id or proxy.throughId(string | entityRef)(optional) — Optional entity id or proxy: drop through only its one-way colliders.
Physics.passThrough(player)
Physics.passThrough(player, entity("ledge"))
globals/physics/pinSoftRegion
physics.pinSoftRegion(softId: string | entityRef, region: PhysicsSoftRegion?, opts: { name: string?, target: vec3? }?) -> string
Pin a region of a soft body: its particles are held kinematic, where
they stand now, and the rest of the body hangs from them, rests on them
or swings about them through its elastic elements. A cloth pinned by two
corners hangs; a jelly pinned along its base stays put while its top
wobbles. Give the pin a target (or set one later with
Physics.setPinTarget) and the pinned particles move together so their
centre stands there, dragging the body after them: a hand grabbing a
corner, a press driven down into a block. The pin is an entry of the soft
body's SoftBody component (pins), so it is saved with the scene,
reaches every peer and is made again on a rebuilt body; it reads back
from Physics.softBodyState(softId).pins.
Parameters
softIdstring | entityRef— The soft body's entity (it carries aSoftBodycomponent).regionPhysicsSoftRegion(optional) — Which particles to pin, asPhysics.softRegiontakes it:{ box = { min, max } }or{ nearest = point }in the entity's unit box (-0.5 to 0.5 on each axis),space = "world"for world coordinates; nil pins the whole body.opts{ name: string?, target: vec3? }(optional) —{ name: string?, target: vec3? }: the name the pin is addressed by (by defaultpin1,pin2, ...), and a world position to move the pinned particles' centre to.
Returns string — The pin's name.
local corner = Physics.pinSoftRegion(cloth, { nearest = {-0.5, 0, 0.5} })
Physics.pinSoftRegion(cloth, { box = { min = {-0.5, -1, 0.45}, max = {0.5, 1, 0.5} } }, { name = "top" })
local grab = Physics.pinSoftRegion(jelly, { nearest = hit.point, space = "world" }, { target = hit.point })
globals/physics/planeHold
physics.planeHold(entityId: string | entityRef) -> PhysicsPlaneHold?
Which plane holds a body, and where the hold comes from: the
PlaneHold covering the body (on its entity or an ancestor, a group
hold over its collision groups, or a world hold), as the physics world
applied it. A rigid or a soft body answers alike.
Parameters
entityIdstring | entityRef— Entity id or proxy of a body.
Returns PhysicsPlaneHold? — A PhysicsPlaneHold (normal, point, holder, covers), or nil when no hold holds the body (or nothing in the scene answers to that id).
local h = Physics.planeHold(crate); if h then print(h.holder, h.covers, h.normal.z) end
globals/physics/playReplay
physics.playReplay(opts: (table | boolean)?) -> PhysicsReplayInfo
Play the recorded replay back, or steer the one playing: slow motion,
fast forward, reverse, a jump to a recorded second (scrubbing), a loop.
Every recorded entity is drawn where it was at the replay's time, blended
between the recorded steps either side of it; whatever is parented under
a body (wheels, its model) moves with it, a soft body takes the shape its
recorded particles held, and a ragdoll's bones their recorded poses. The
replay draws and nothing more: the live simulation holds still while
gameplay is paused (engine.paused = true) or steps on underneath while
it runs, and every read of it (entity.position, velocities,
Physics.stateDigest) answers the live state, so the simulation is
exactly where it was when the replay ends. Physics.drawnPose answers
the replayed pose (replayed = true), so a camera following a body's
drawn pose follows it through the replay, and any camera can watch it.
The replay moves on the frame clock at rate recorded seconds per
second, whatever engine.timeScale is, and stops at the end it runs to
unless it loops. Pass false to end it: everything is drawn where the
simulation holds it again.
Parameters
opts(table | boolean)(optional) —{ rate?, time?, loop? }:rate(1 by default, -64 to 64) in recorded seconds per second: 0.25 for quarter-speed slow motion, negative to play backwards, 0 to hold a moment;timejumps to that recorded second (Physics.replayInfo().fromto.to);loop = truewraps around. A replay started with notimestarts at the first recorded step, or the last for a negative rate. Fields left out keep what the playing replay has.falseends the replay.
Returns PhysicsReplayInfo — A PhysicsReplayInfo, with the replay's time and rate.
engine.paused = true; Physics.playReplay({ rate = 0.25 })
local info = Physics.replayInfo(); Physics.playReplay({ time = info.to - 2, rate = 0 })
Physics.playReplay({ rate = -1 })
Physics.playReplay(false); engine.paused = false
globals/physics/probeMotion
physics.probeMotion(target: string | entityRef, opts: PhysicsMotionProbeOptions?) -> () -> ()
Place a motion probe: a measuring point on a body (an accelerometer, a
g-force sensor) whose velocity, acceleration, angular velocity and angular
acceleration the physics step samples, for Physics.motionSamples and
Physics.motionPeak to read. On a rigid body it measures a point of the
body, the rotation terms (centripetal and tangential acceleration)
included, at every solver substep: the rate the solver actually steps the
body, which rises when the body's island runs extra substeps. A step the
solver does not move the body in (asleep, settled) takes one sample. On a
soft body it measures a region's particles, their velocity averaged by
mass, at the same rate: a hit soft body's extra substeps are each sampled.
Each sample also
reads the proper acceleration, what a rider or sensor at the point feels
(0 g in free fall, 1 g at rest), and its size in g. Use it for g-force
readouts, impact severity, crash and hit strength, controller haptics,
flight and roller-coaster feel, and telemetry. A body with no probe costs
nothing. The probe follows the entity id across a mode switch or a
respawn, and each new body it measures (play starting, a respawn) starts
its record afresh: the samples, the peak and the clock. It ends when the
returned function 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.
Parameters
targetstring | entityRef— The entity whose body to measure: a rigid body, or withopts.regiona soft body.optsPhysicsMotionProbeOptions(optional) —PhysicsMotionProbeOptions:{ point?, region?, name?, capacity?, substeps? }.
Returns () -> () — A function that removes the probe and drops what it kept.
local stop = Physics.probeMotion(car, { point = {0, 0.6, -0.3}, name = "seat" })
Physics.probeMotion(ball)
Physics.probeMotion(dummy, { region = { nearest = {0, 0.4, 0} }, name = "head" })
globals/physics/pumpContactEvents
physics.pumpContactEvents()
Deliver every collision and contact event the physics steps recorded
since the last delivery to the onContact, onImpact and onTrigger
listeners and the lists listenContacts keeps. The engine calls this
after every physics step that recorded any, before that step's
fixedUpdate, so listeners hear each step's events at the physics rate.
Physics.pumpContactEvents()
globals/physics/pumpJointBreaks
physics.pumpJointBreaks()
Deliver every joint break the simulation has recorded to the registered
listeners. The engine calls this after every physics step that broke a
joint, before that step's fixedUpdate, so listeners hear each break at
the physics rate whichever way the joint was made.
Physics.pumpJointBreaks()
globals/physics/pumpLatches
physics.pumpLatches()
Deliver every latch the simulation made since the last delivery: join
each latched pair of Latch points with its joint and run the listeners
Physics.onLatch / Physics.onUnlatch registered. The engine calls this
after every physics step that latched or freed a point, before that
step's fixedUpdate, so the step that follows holds the joint.
Physics.pumpLatches()
globals/physics/pumpSoftBodyTears
physics.pumpSoftBodyTears()
Give every piece the soft bodies tore off since the last call its
entity, and deliver each tear to the onSoftBodyTear listeners. Every
SoftBody component calls this each frame, so tears are handled on their
own; the work is done once per frame however many call it.
Physics.pumpSoftBodyTears()
globals/physics/pumpWaterEvents
physics.pumpWaterEvents()
Deliver every entry into and exit from the water the physics steps
recorded since the last delivery to the Physics.onWater listeners. The
engine calls this after every physics step that recorded any, before
that step's fixedUpdate, so listeners hear each one at the physics rate.
Physics.pumpWaterEvents()
globals/physics/raycast
physics.raycast(origin: vec3, direction: vec3, maxDistance: number?, exclude: (string | {string})?, options: PhysicsCastOptions?) -> PhysicsHit?
Cast a ray and return the first hit. Answers from COLLIDERS ALONE: a
mesh that renders but carries no collider is not in the physics world, so a
ray fired through it reports the same nil a ray through open air does.
renderer.raycast answers the same ray against the geometry the renderer
DRAWS, which is what reads the surface of a terrain, a procedurally
generated mesh, or any plain Model.
A trigger (isTrigger) holds nothing up, so the ray passes through it.
Many rays a frame (a crowd's sight lines, a flock's probes, many
projectiles): Physics.castMany answers them all in one call.
Parameters
originvec3— Ray origin in world space.directionvec3— Ray direction, of any length: the engine normalises it, somaxDistanceanddistanceare world units.maxDistancenumber(optional) — Maximum distance along the ray (defaults to 1000).exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits.optionsPhysicsCastOptions(optional) — OptionalPhysicsCastOptions:{ mover = entity }casts for the entity the cast moves (a character controller, or anything moved by casts), so it meets colliders as that entity's body does: a one-way collider (oneWay) answers only on the face its direction points out of, to a cast that starts outside it; a collider whosecontactTagthe contact filter answers "ignore" or "sensor" with a tag of the mover's own colliders is passed; and the one-way collidersPhysics.passThrough(mover)drops the mover through are passed until it is clear of them.
Returns PhysicsHit? — Hit table { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }, or nil if nothing hit. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. surfaceVelocity is the collider's surfaceVelocity in world space (m/s), the motion its surface carries what stands on it with, and is absent for a collider whose surface holds still. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is. A nil says the ray met no COLLIDER, which Physics.colliderCount() separates from a world that holds none for it to meet.
local hit = Physics.raycast({x=0,y=2,z=0}, {x=0,y=-1,z=0})
local hit = Physics.raycast(origin, dir, 50, { selfId, carriedId })
local ground = Physics.raycast(feet, {x=0,y=-1,z=0}, 0.3, selfId, { mover = selfId })
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
if Physics.colliderCount() == 0 then hit = renderer.raycast(eye, down, 200) end
globals/physics/raycastAll
physics.raycastAll(origin: vec3, direction: vec3, maxDistance: number?, maxHits: number?, exclude: (string | {string})?, options: PhysicsCastOptions?) -> { PhysicsHit }
Cast a ray and return every hit up to maxHits. Answers from COLLIDERS
ALONE, so a rendered mesh with no collider is absent from the result;
renderer.raycastAll answers the same ray against the geometry the
renderer draws.
A trigger (isTrigger) holds nothing up, so the ray passes through it.
Parameters
originvec3— Ray origin in world space.directionvec3— Ray direction, of any length: the engine normalises it, somaxDistanceanddistanceare world units.maxDistancenumber(optional) — Optional distance limit along the ray.maxHitsnumber(optional) — Optional cap on the number of hits returned.exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits.optionsPhysicsCastOptions(optional) — OptionalPhysicsCastOptions:{ mover = entity }casts for the entity the cast moves (a character controller, or anything moved by casts), so it meets colliders as that entity's body does: a one-way collider (oneWay) answers only on the face its direction points out of, to a cast that starts outside it; a collider whosecontactTagthe contact filter answers "ignore" or "sensor" with a tag of the mover's own colliders is passed; and the one-way collidersPhysics.passThrough(mover)drops the mover through are passed until it is clear of them.maxHitscounts the hits the mover meets.
Returns { PhysicsHit } — Array of hit tables { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }: empty when nothing was hit. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. surfaceVelocity is the collider's surfaceVelocity in world space (m/s), the motion its surface carries what stands on it with, and is absent for a collider whose surface holds still. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is.
local hits = Physics.raycastAll(origin, dir, 50, 4)
globals/physics/raycastBetween
physics.raycastBetween(fromId: string | entityRef, toId: string | entityRef, maxDistance: number?) -> PhysicsHit?
Cast a ray from one entity toward another and return the first hit. The ray runs from the source's world position toward the target's world position, wherever each sits in the hierarchy, and passes over the source's own colliders: those of the body it rides (its own body, or the body of its nearest ancestor carrying one) and of every entity riding that body. With nothing between them, the first hit is the target's collider.
Parameters
fromIdstring | entityRef— Origin entity, an id or a proxy.toIdstring | entityRef— Target entity, an id or a proxy.maxDistancenumber(optional) — Optional distance cap (default 1000).
Returns PhysicsHit? — PhysicsHit, or nil if the entities are coincident or nothing was hit before the target's position. Raises naming the argument when fromId or toId names no entity.
local hit = Physics.raycastBetween(a, b)
globals/physics/raycastScreen
physics.raycastScreen(sx: number, sy: number, maxDistance: number?, exclude: (string | {string})?) -> PhysicsHit?
Cast a ray from a screen pixel into the scene and return the first hit. Unprojects the pixel with screenToRay, then casts with raycast.
Parameters
sxnumber— Screen X in the scene viewport's physical pixels, measured from the top-left of the rect the scene is drawn into: the space ofinput.snapshot().mouse_position,worldToScreenandscreenToRay. A point in the UI's logical points (a widget's position,ui.screenSize()coordinates) is carried here byui.toViewport(x, y).synumber— Screen Y in the same space assx.maxDistancenumber(optional) — Maximum distance along the ray (defaults to 1000, matchingraycast).exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits.
Returns PhysicsHit? — Hit table { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }, or nil on a miss or when no camera has rendered yet. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is.
local Zin = require("@builtin::modules.zinput")
local x, y = Zin.state.mousePosition(); local hit = Physics.raycastScreen(x, y)
globals/physics/recordDigests
physics.recordDigests(opts: (table | boolean)?) -> table
Record the state digest of every physics step from now on, as
Physics.stateDigest takes it when the step ends, keeping the most recent
steps of them for Physics.digestLog. Two engines that run the same
steps each record, then compare their logs with Physics.firstDivergence
to find the first step, body and field where their simulations parted.
A run repeated in the same engine, the first run despawned before it,
records the same steps as the first, so one engine checks a scene
against its own earlier run (Physics.stateDigest states the
conditions). Pass false to stop; what was recorded stays readable. Starting again
drops the earlier recording. The recording is the engine's, so a worker
job reads and changes the same one.
Parameters
opts(table | boolean)(optional) — ThePhysics.stateDigestoptions plussteps(600 by default, at most 100000). Each step keeps its entries (so a divergence names the body) unlessentries = false;values = truealso keeps the numbers (so it names the field).falsestops recording.
Returns table — { recording, steps, recorded }.
Physics.recordDigests({ steps = 1200, key = "name", values = true })
Physics.recordDigests(false)
globals/physics/recordReplay
physics.recordReplay(opts: (table | boolean)?) -> PhysicsReplayInfo
Record a replay of the physics simulation from now on: at the end of
every step, the pose and velocities of each rigid body and ragdoll bone,
the pose and particles of each soft body, and each moment two of their
colliders begin or stop touching. It keeps the most recent seconds
inside maxBytes, dropping the oldest steps past either, so a game can
record all the time and play the last few seconds back on demand: an
instant replay, a crash replay, a kill cam, a ghost. Play it with
Physics.playReplay, read it with Physics.replayFrame and
Physics.replayContacts, keep it with Physics.saveReplay. Pass false
to stop; what was recorded stays to play. Starting again drops the earlier
recording. A recording belongs to the play session it ran in: leaving
play stops it and ends a replay, keeping what it holds. Recording runs
inside the step at the step rate, in play or
while Physics.advance steps; Physics.replayInfo reports its size, its
bytes per recorded second and what it costs a step.
Parameters
opts(table | boolean)(optional) —{ entities?, seconds?, maxBytes?, contacts? }:entities, an array of entity ids, records those entities (any body type), by default every entity whose body moves (dynamic and kinematic bodies, ragdoll bones, soft bodies);seconds(30 by default, at most 3600) is how much recent simulation it keeps;maxBytes(64 MiB by default, 64 KiB to 1 GiB) bounds its memory;contacts = falseleaves the contacts out.falsestops recording.
Returns PhysicsReplayInfo — A PhysicsReplayInfo.
Physics.recordReplay({ seconds = 10 })
Physics.recordReplay({ entities = { car, wall }, seconds = 5 })
Physics.recordReplay(false)
globals/physics/releaseLatch
physics.releaseLatch(id: string | entityRef) -> boolean
Release the latch an entity's Latch point holds: its joint comes off,
both points are freed and Physics.onUnlatch hears reason "release". A
freed point latches again once it has stood clear of every point it
latches to, so pulling apart and backing in again re-latches. A latch with
lock = "permanent" on either point holds until its joint breaks or a
point is removed, and refuses, naming the point.
Parameters
idstring | entityRef— The entity carrying the Latch (either point of the pair).
Returns boolean — true when a latch was released, false when the point was free.
Physics.releaseLatch(trailerCoupler)
globals/physics/releasePin
physics.releasePin(softId: string | entityRef, name: string?) -> number
Release a pin of a soft body, or every pin: its particles take their mass back, keep the velocity they had, and move with the body again.
Parameters
softIdstring | entityRef— The soft body's entity.namestring(optional) — The pin to release; omit to release every one.
Returns number — How many pins were released.
Physics.releasePin(cloth, corner)
Physics.releasePin(cloth)
globals/physics/removeCollider
physics.removeCollider(entityId: string | entityRef) -> string?
Remove whichever collider component an entity carries.
Parameters
entityIdstring | entityRef— Target entity id.
Returns string? The component that was removed, or nil when there was none.
Physics.removeCollider(id)
globals/physics/removeConstraint
physics.removeConstraint(entityId: string | entityRef, index: number?)
Remove transform constraints from an entity (if any are present).
Parameters
entityIdstring | entityRef— Target entity id.indexnumber(optional) — Optional constraint index (currently ignored — the whole component is removed).
Physics.removeConstraint(id)
globals/physics/removeJoint
physics.removeJoint(entityId: string | entityRef | table, name: string?)
Remove one joint, leaving every other joint on its bodies standing:
the Joint an entity carries (its unnamed one, or the one name names),
or the Joint component given itself, as Physics.addJoint returns it.
Parameters
entityIdstring | entityRef | table— Target entity id, or aJointcomponent.namestring(optional) — The Joint's name on that entity; omit for its unnamed Joint.
Physics.removeJoint(id)
Physics.removeJoint(beam, "right")
local grab = Physics.addJoint(hand, crate); Physics.removeJoint(grab)
globals/physics/removeSurface
physics.removeSurface(name: string)
Remove a surface Physics.defineSurface defined. Colliders naming it
keep the name and collide with their own coefficients from the next step.
Parameters
namestring— The surface's name.
Physics.removeSurface("ice")
globals/physics/removeWater
physics.removeWater(name: string)
Remove a body of water Physics.defineWater defined.
Parameters
namestring— The body's name.
Physics.removeWater("pool")
globals/physics/removeWheelCollider
physics.removeWheelCollider(entityId: string | entityRef)
Remove the WheelCollider component from an entity (if present).
Parameters
entityIdstring | entityRef— Target entity id.
Physics.removeWheelCollider(id)
globals/physics/removeWind
physics.removeWind(name: string)
Remove a wind field Physics.defineWind defined.
Parameters
namestring— The field's name.
Physics.removeWind("breeze")
globals/physics/repairSoftBody
physics.repairSoftBody(softId: string | entityRef) -> number
Restore the shape a soft body was built in: every permanent dent,
crumple and crease it took past its plasticYield is undone, and the body
is put back in that shape where it stands, keeping its motion as a whole. The repair is the
SoftBody component's repairs count raised by one, so it reaches every
peer. Physics.softBodyState(softId).plastic reads 0 once it is applied
(at the start of the next frame), and a Physics.setSoftParticles made
before then is put back in the built shape with the rest of the body.
Parameters
softIdstring | entityRef— The soft body's entity (it carries aSoftBodycomponent).
Returns number — The component's new repairs count.
Physics.repairSoftBody(shell)
globals/physics/replayContacts
physics.replayContacts(opts: table?) -> { PhysicsReplayContact }
Read the contacts the replay recording kept, oldest first: each
moment two colliders of the recorded entities began (kind = "begin")
or stopped ("end") touching, the two entities by id, and for a begin
where they touched, the normal from a to b, the impulse and how fast
they were closing. A replay plays its sounds and sparks at these moments.
Parameters
optstable(optional) —{ from?, to? }: the recorded seconds to read between (inclusive).
Returns { PhysicsReplayContact } — An array of PhysicsReplayContact.
for _, c in Physics.replayContacts() do if c.kind == "begin" then print(c.time, c.a, c.b, c.impulse) end end
globals/physics/replayFrame
physics.replayFrame(opts: table?) -> PhysicsReplayFrame?
Read the recorded state at one recorded second, blended between the steps either side of it the way a replay draws it: a plot synced to a replay's timeline, a ghost placed at a recorded pose, a check that what was drawn is what was recorded.
Parameters
optstable(optional) —{ time?, velocities? }:time(the playing replay's time, else the last recorded step) is held inside the recording;velocities = trueadds each body'slinvel/angveland each soft body's particlevelocities.
Returns PhysicsReplayFrame? — A PhysicsReplayFrame, or nil when nothing was recorded.
local f = Physics.replayFrame({ time = 1.5 }); print(f.bodies[car].position.y)
globals/physics/replayInfo
physics.replayInfo() -> PhysicsReplayInfo
What the replay recording holds and what the replay playing it does:
whether it is recording and playing, the recorded seconds it spans
(from, to, duration), its steps and stepRate, what its last step
holds (bodies, bones, softBodies, particles), the contacts it
keeps, its memory (bytes, and bytesPerSecond per recorded second),
and what recording took a step (recordMs mean, recordMsMax). While a
replay plays: its time, rate, loop, ended once it ran to an end,
and missing, the keys of the recorded tracks the scene holds nothing to
draw on (an entity id or ragdoll bone it does not hold, or a soft body of
another particle count), which stay drawn where the live simulation holds
them.
Returns PhysicsReplayInfo — A PhysicsReplayInfo.
local info = Physics.replayInfo(); print(info.duration, info.bytesPerSecond, info.recordMs)
globals/physics/restore
physics.restore(snapshot: PhysicsSnapshot) -> PhysicsRestore
Put the physics simulation back to a snapshot Physics.snapshot took
or Physics.loadSnapshot read: bodies, joints, soft bodies, contacts,
each entity's transform and velocity, and the settings of every
component the solver is built from stand as they stood, so a setting
written since reads back the snapshot's value, the value the solver
simulates with, and the next steps
run exactly as they ran from it. A joint that broke since comes back, and
a wheel that came off its vehicle since goes back on. The
world has to hold the bodies the snapshot was taken over (the same
entities with the same bodies, colliders, soft bodies and joints,
whatever order the world built them in); the restore is refused,
changing nothing, when an entity it holds is gone, an entity has a body
it does not hold (made since: remove it first) or an entity's bodies,
colliders or soft body differ from the snapshot's, or a component the
solver is built from was added to or removed from an entity since, and
the error names every such entity. Forces, drives and kinematic moves queued for the coming steps
stay queued, and listeners, recordings and probes keep running.
Parameters
snapshotPhysicsSnapshot— A snapshot.
Returns PhysicsRestore — What was put back, with the restore's wall time in ms.
local start = Physics.snapshot(); Physics.advance(300); Physics.restore(start)
local ok, why = pcall(Physics.restore, start); if not ok then print(why) end
globals/physics/resumeReplay
physics.resumeReplay(time: number?) -> PhysicsReplayFrame
Carry the live simulation to a recorded second and go on from there:
puzzle undo, a retry from just before the crash, a replay a player takes
over. It ends the replay, then writes the state the recording holds at
time into the simulation: each recorded rigid body's pose and linear
and angular velocity, and each recorded soft body's particle positions
and velocities (Physics.setSoftParticles). The simulation steps on from
that state once gameplay runs. Ragdoll bones, joints' carried impulses
and a soft body's plastic flow carry on from the live state.
Parameters
timenumber(optional) — The recorded second (the playing replay's time by default, else the last recorded step).
Returns PhysicsReplayFrame — The PhysicsReplayFrame written.
engine.paused = true; Physics.resumeReplay(Physics.replayInfo().to - 3); engine.paused = false
globals/physics/runStepHooks
physics.runStepHooks(phase: string, dt: number, step: number)
Run the step hooks registered for one side of a physics step. The
engine calls this with "before" at the start of every step and with
"after" at its end while Physics.onBeforeStep or
Physics.onAfterStep hooks are registered.
Parameters
phasestring—"before"or"after".dtnumber— The step's length in seconds.stepnumber— The step's number.
Physics.runStepHooks("before", 1 / 30, 1)
globals/physics/saveReplay
physics.saveReplay() -> string
The replay recording as a string of bytes, the same on every
platform: keep it with vfs.write, play it again with
Physics.loadReplay here or in another engine (a native engine's
recording plays in a browser engine and the other way round).
Returns string — The recording's bytes.
vfs.write("/source/replays/crash.replay", Physics.saveReplay())
globals/physics/setAngularDamping
physics.setAngularDamping(entityIdOrDamping: string | entityRef | number, damping: number?)
Set angular damping on an entity's rigid body. One-arg form targets the script-context entity.
Parameters
entityIdOrDampingstring | entityRef | number— The entity's id or proxy (withdamping) OR the damping value (script-context entity).dampingnumber(optional) — Optional explicit damping when targeting another entity.
Physics.setAngularDamping(0.1)
Physics.setAngularDamping(entityId, 0.1)
globals/physics/setAngularVelocity
physics.setAngularVelocity(a: string | entityRef | number | vec3, b: (number | vec3)?, c: number?, d: number?)
Set the angular velocity of an entity (radians/sec). Same call
shapes as setVelocity.
Parameters
astring | entityRef | number | vec3— x-component, a{x, y, z}vector, or the target (explicit): the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.b(number | vec3)(optional) — y-component, x-component, or the vector depending on call form.cnumber(optional) — z-component or y-component depending on call form.dnumber(optional) — Optional z-component when targeting an explicit entity.
Physics.setAngularVelocity(0, 0, 1)
Physics.setAngularVelocity(entityId, 0, 0, 1)
Physics.setAngularVelocity(entityId, {x=0, y=0, z=1})
globals/physics/setBodyType
physics.setBodyType(entityId: string | entityRef, bodyType: string)
Change a rigid body's type at runtime. Mass, colliders, and joints are preserved — only the body's response to forces and position writes changes.
Parameters
entityIdstring | entityRef— Target entity id.bodyTypestring— One of"dynamic","kinematic","static".
Physics.setBodyType(entityId, "kinematic")
globals/physics/setCcdEnabled
physics.setCcdEnabled(entityIdOrEnabled: string | entityRef | boolean, enabled: boolean?)
Enable or disable continuous collision detection on an entity's rigid body. One-arg form targets the script-context entity.
Parameters
entityIdOrEnabledstring | entityRef | boolean— The entity's id or proxy (withenabled) OR the boolean (script-context entity).enabledboolean(optional) — Optional explicit boolean when targeting another entity.
Physics.setCcdEnabled(true)
Physics.setCcdEnabled(entityId, true)
globals/physics/setCollisionGroups
physics.setCollisionGroups(entityId: string | entityRef, membership: number, filter: number)
Set the collision-group membership and filter bitmasks on an
entity's colliders. Adds a CollisionGroup component if missing; the
component holds the groups, so they apply to the colliders of the
entity's rigid body, its standalone collider (a collider with no
Physics is a static collider) and the shape it composes onto an
ancestor's body, and a body or collider built or rebuilt later takes
them as it is built, in edit mode as well as play. A shape a child
entity composes onto a body takes the child's groups when the child has
a CollisionGroup of its own, and the body entity's otherwise, so one
body can carry shapes in different groups. An entity with no collider
and no body logs a warning naming it, since its groups reach no collider
until one is added. A soft body's groups are its SoftBody component's
collisionMemberships and collisionFilter. A vehicle's
WheelColliders stand only on colliders its chassis' groups collide
with.
Parameters
entityIdstring | entityRef— Target entity id.membershipnumber— Bitmask: which groups this collider belongs to.filternumber— Bitmask: which groups this collider can collide with.
Physics.setCollisionGroups(id, 0x0001, 0xFFFF)
globals/physics/setContactFilter
physics.setContactFilter(tagA: string, tagB: string, mode: string?)
Decide what happens when two kinds of collider meet, by tag: every
collider component carries a contactTag field, and the world's contact
filter answers a pair of tags with a mode. "ignore": the two pass
through each other and report nothing (a team's shots through its own
players, ghosts through walls). "sensor": the two report their contacts
(Physics.contacts, Physics.onContact) and push nothing (a pickup a
player runs through, a shield that only registers hits). "solid": the
two collide, which every pair the filter does not name does; it takes
the entry out. A tag may be paired with itself. The filter is data the
physics step reads, so it costs no script per contact. It applies from
the next physics step, to colliders already touching as well, and lasts
until changed. A pair collision groups or Physics.ignoreCollision
keep apart stays apart whatever the filter says. A vehicle's
WheelColliders pass a collider the filter answers "ignore" or
"sensor" with its chassis' tag, as the chassis does.
Parameters
tagAstring— A contact tag, 1 to 64 bytes.tagBstring— Another contact tag (or the same one).modestring(optional) — "ignore", "sensor" or "solid"; nil is "solid".
Physics.setContactFilter("redTeam", "redShot", "ignore")
Physics.setContactFilter("player", "coin", "sensor")
entity("shot").component.add("SphereCollider", { radius = 0.1, contactTag = "redShot" })
globals/physics/setGravity
physics.setGravity(gravity: vec3)
Replace the world gravity vector.
Parameters
gravityvec3— New gravity vector in m/s².
Physics.setGravity({x=0, y=-9.81, z=0})
globals/physics/setGravityScale
physics.setGravityScale(entityIdOrScale: string | entityRef | number, scale: number?)
Set the per-entity gravity scale (1.0 = normal, 0.0 = no gravity). One-arg form targets the script-context entity.
Parameters
entityIdOrScalestring | entityRef | number— The entity's id or proxy (withscale) OR the scale value (script-context entity).scalenumber(optional) — Optional explicit scale when targeting another entity.
Physics.setGravityScale(0.5)
Physics.setGravityScale(entityId, 0.5)
globals/physics/setJointMotor
physics.setJointMotor(entityId: string | entityRef | table, targetVelocity: number, maxForce: number, name: string?)
Drive an entity's joint motor at targetVelocity with at most
maxForce. The joint is the one entityId carries, or, when it carries
none, the joint it is the connected end of. Writes the joint's own motor
fields (motorMode = "velocity", motorVelocity, motorMaxForce), so the
motor is component data that syncs and reads back. A hinge turns at
radians per second under newton-metres, a prismatic slides at metres per
second under newtons, a ball joint drives each of its angles (velocity 0
holds it still: joint friction up to maxForce), a generic joint every
free axis. For a target angle or travel set motorMode = "position" and
motorTarget on the Joint; for single axes, its axisMotors. A Joint
given a yieldForce or yieldTorque refuses, its yield holding the axes
the motor would drive.
Parameters
entityIdstring | entityRef | table— Entity carrying the Joint component, or the body it connects to, or aJointcomponent.targetVelocitynumber— Velocity the motor holds: rad/s for an angle, m/s for a travel.maxForcenumber— The most force or torque the motor applies; 0 leaves it uncapped.namestring(optional) — The Joint's name on that entity, for one of several joints; omit for its unnamed Joint.
Physics.setJointMotor(wheel, 10, 50)
Physics.setJointMotor(piston, 0.5, 2000)
Physics.setJointMotor(arm, 2, 300, "elbow")
globals/physics/setLinearDamping
physics.setLinearDamping(entityIdOrDamping: string | entityRef | number, damping: number?)
Set linear damping on an entity's rigid body (0 = no damping). One-arg form targets the script-context entity.
Parameters
entityIdOrDampingstring | entityRef | number— The entity's id or proxy (withdamping) OR the damping value (script-context entity).dampingnumber(optional) — Optional explicit damping when targeting another entity.
Physics.setLinearDamping(0.05)
Physics.setLinearDamping(entityId, 0.05)
globals/physics/setMass
physics.setMass(entityIdOrMass: string | entityRef | number, mass: number?)
Set the mass of an entity's rigid body (kg). One-arg form targets the script-context entity.
Parameters
entityIdOrMassstring | entityRef | number— Entity id (withmass) OR mass value (script-context entity).massnumber(optional) — Optional explicit mass when targeting another entity.
Physics.setMass(10)
Physics.setMass(entityId, 10)
globals/physics/setPinTarget
physics.setPinTarget(softId: string | entityRef, name: string, position: vec3?)
Drive a pin of a soft body to a world position: its particles move
together over the next step so the centre they had when the pin was made
stands at position, with the velocity that carries them there, and the
rest of the body follows. Set it every frame to drag the region along a
path. nil stops driving it and holds it where it stands. The target is
the pin's entry in the SoftBody component's pins, so it reaches every
peer.
Parameters
softIdstring | entityRef— The soft body's entity.namestring— The pin's name, aspinSoftRegionreturned it.positionvec3(optional) — The world position for the pinned particles' centre; nil holds them where they stand.
Physics.setPinTarget(cloth, corner, {x=2, y=3, z=0})
globals/physics/setRotationLocks
physics.setRotationLocks(entityId: string | entityRef, x: boolean, y: boolean, z: boolean)
Lock or unlock rotation on specific axes.
Parameters
entityIdstring | entityRef— Target entity id.xboolean— Lock rotation about the world X axis.yboolean— Lock rotation about the world Y axis.zboolean— Lock rotation about the world Z axis.
Physics.setRotationLocks(id, false, true, false)
globals/physics/setSoftParticles
physics.setSoftParticles(softId: string | entityRef, particles: PhysicsSoftParticlesWrite) -> number?
Write a soft body's particles: where each stands, how fast it
moves, and where it stands in the body's rest shape, the shape it springs
back to. The body simulates on from the written state, so a shape read
once can be put back: a replay or a rewind, a saved game holding a
damaged object, a level that starts with something already bent, a
correction from the network, a repair that pushes one dent out. The
write is applied at once on the peer that simulates the body: a read
straight after sees it, and the next physics step starts from it. Written
from Physics.onBeforeStep, it is the state that step starts from, ahead
of the step's drives, tears and solve. positions and velocities move
the particles and leave the rest shape as it was, so the body springs
back from a written shape toward its rest shape (a dent past its
plasticYield can then set); restPositions changes the rest shape
itself, the permanent part of the shape, which stays once the body
settles, the way a dent past the yield stays (Physics.softBodyState(id) .plastic reads it, and Physics.repairSoftBody undoes it). A read's
restPositions are where each particle rests, which a crumple's elements
pull the body away from, so to keep the shape a body stands in after a
crash, write its positions as restPositions. Positions are
written first and the body's frame fitted to them, then the rest places
are measured through that frame, and each element of the body 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 the written dent 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 it 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, so two rewinds to one read fall the same way, and the
frame after a write draws the body where it was written, paused or not.
A rewind starts from the read alone, while the run the read came from
carried on with what the solver had built up, so the two can part by
rounding where a hit amplifies it; writing the read back the moment it is
taken (from Physics.onBeforeStep) makes that run a replay of it too.
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 repair (Physics.repairSoftBody) applies at the start of the next
frame and puts the body back in its built shape over a write made before
it; a written restPositions in the built shape is the same repair, at
once. A pinned particle stands where it is written and its pin holds it
there, whatever velocity is written to it (a read before the next step
reads that velocity; the step keeps the particle in place).
A Physics.softParticles read is a write of this shape, so
Physics.setSoftParticles(id, read) puts back the particles it read,
their rest places included.
Parameters
softIdstring | entityRef— The soft body's entity (it carries aSoftBodycomponent).particlesPhysicsSoftParticlesWrite—PhysicsSoftParticlesWrite:indices(zero-based, asPhysics.softParticlesreads them; omit to write every particle in order) and any ofpositions,velocitiesandrestPositions, one value per named particle, in world space.
Returns number? — How many particles were written; nil from a worker VM, whose write the engine thread applies.
local saved = Physics.softParticles(shell); if saved then Physics.setSoftParticles(shell, saved) end -- later: put the shell back as it was
local bent = Physics.softParticles(bar); if bent then Physics.setSoftParticles(bar, { restPositions = bent.positions }) end -- the shape it stands in becomes its rest shape
Physics.setSoftParticles(jelly, { indices = { 0, 7 }, velocities = { {x=0, y=3, z=0}, {x=0, y=3, z=0} } })
globals/physics/setTranslationLocks
physics.setTranslationLocks(entityId: string | entityRef, x: boolean, y: boolean, z: boolean)
Lock or unlock translation on specific axes.
Parameters
entityIdstring | entityRef— Target entity id.xboolean— Lock translation along the world X axis.yboolean— Lock translation along the world Y axis.zboolean— Lock translation along the world Z axis.
Physics.setTranslationLocks(id, false, false, true)
globals/physics/setVelocity
physics.setVelocity(a: string | entityRef | number | vec3, b: (number | vec3)?, c: number?, d: number?)
Set the linear velocity of an entity. Accepts (x, y, z) or a
{x, y, z} vector for the script-context entity, or the same
prefixed with an explicit entityId.
Parameters
astring | entityRef | number | vec3— x-component, a{x, y, z}vector, or the target (explicit): the body's entity id or proxy, or an entity a collider of it was authored on (a hit'sentityIdorbody, an overlap's id); static world geometry such as the ground, like a static body, stays where it stands.b(number | vec3)(optional) — y-component, x-component, or the vector depending on call form.cnumber(optional) — z-component or y-component depending on call form.dnumber(optional) — Optional z-component when targeting an explicit entity.
Physics.setVelocity(0, 10, 0)
Physics.setVelocity(entityId, 0, 10, 0)
Physics.setVelocity(entityId, {x=0, y=10, z=0})
globals/physics/setWaterVolume
physics.setWaterVolume(target: string | entityRef, volume: PhysicsWaterVolume?) -> () -> ()
Measure an entity in the water by a volume stated in its own frame
(its position and turn, unscaled, metres) in place of its body,
colliders or origin: what a character moved by casts, with no body of its
own, is measured by (a CharacterController states its capsule).
Physics.onWater and Physics.immersion read it from then on, and a
listener for every body (Physics.onWater(nil, fn)) watches it. An
entity with no rigid or soft body of its own is heard by triggers by the
same volume (Physics.onTrigger): it enters and leaves a trigger as a
body does. The
volume stands until the returned function is called, or the component
that stated it is removed or its entity destroyed; the latest volume
still standing is the one the entity is measured by.
Parameters
targetstring | entityRef— The entity.volumePhysicsWaterVolume(optional) — APhysicsWaterVolume:{ shape = "capsule", radius, height, center? }(standing along its up axis,heightfrom the bottom of the lower cap to the top of the upper one),{ shape = "sphere", radius, center? }or{ shape = "box", size, center? }; nil takes every volume stated for it away, so it is measured by its body, collider or origin again.
Returns () -> () — A function that takes this volume away again.
local off = Physics.setWaterVolume(diver, { shape = "capsule", radius = 0.3, height = 1.8, center = vector.create(0, 0.9, 0) })
Physics.setWaterVolume(buoy, { shape = "sphere", radius = 0.4 })
globals/physics/shaftNetworkState
physics.shaftNetworkState(entityId: string | entityRef) -> table?
Read a ShaftNetwork (a drivetrain, gearbox, differential, clutch,
gear train, winch or other network of rotating parts on shafts) as of the
last physics tick: every part's speed and torques and every link's torque,
slip and lock, by name. The same reading as the component's state().
Parameters
entityIdstring | entityRef— The entity carrying the ShaftNetwork.
Returns table? — { parts, links, settled }, or nil when the entity carries none. settled is whether the tick held every link, friction, brake and drive where its bounds allow (every shaft and gear at its ratio, every differential at the mean of its sides, every clutch and lock holding inside its capacity or slipping at it); false when the links ask for speeds the parts cannot take together (a part shafted to two immovable parts turning at different speeds), and the parts then turn as near to every link as they can come. parts.<name> = { speed, rpm, torque, brakeTorque, linkTorque, throttle, brake, wheel?, joint?, problem? }: speed in rad/s (a wheel part's is its wheel's spin, a joint part's its hinge's turn), torque what its source applied (its curve times its throttle plus its constant torque), brakeTorque what its friction, brake and drag applied and linkTorque what the links put on it, all N·m; throttle and brake the inputs in effect; problem why the part turns on its own though it names a wheel or a joint (absent while it turns with it). links.<name> = { kind, ratio, engage, locked, torque, lockTorque, slip, slipping, windup }: ratio, engage and locked the inputs in effect (a gear indicator reads ratio), torque (N·m) the link takes from a (a differential's from input), lockTorque what a differential's lock passes from a to b (or a spring pushes back with), slip how fast a turns against b (rad/s; against ratio times b for a gear), slipping whether a clutch or a differential's lock lets its sides turn apart, windup a spring's wound-up angle (radians).
local s = Physics.shaftNetworkState(car.id); print(s.parts.engine.rpm, s.links.clutch.slipping)
globals/physics/sleep
physics.sleep(entityId: (string | entityRef)?)
Put an entity's rigid body to sleep at rest where it lies, from the
next step. It stays asleep until something wakes it: a contact with a
moving body, a joint to one, a motion setter or Physics.wakeUp. A
resting pile put to sleep stops costing a solve at once instead of after
the half second the solver waits on its own. Raises, naming the body
and why, for a static body and a body whose Physics component sets
canSleep = false. A call made before the body is built (in the turn
its entity takes its Physics component) is applied to the body as it
is built; on an entity that carries no Physics component it does
nothing, and the log says so, naming the entity. A call from a worker
VM is carried out with the frame's other writes, and a refusal of it is
logged as a warning in the same words.
Parameters
entityId(string | entityRef)(optional) — Target entity id or proxy; resolves from script context when omitted.
Physics.sleep(id)
globals/physics/snapshot
physics.snapshot() -> PhysicsSnapshot
Take a snapshot of the whole physics simulation as it stands between
steps, to put the world back to later with Physics.restore: every
rigid body, collider, joint (its limits, motors and the impulses it
carries) and soft body (its particles, elements and plastic state), the
islands, every contact with the impulses it carries into the next step,
the continuous-collision state, the vehicles and their wheels, the
drivetrains, held forces and plane holds, and every entity's transform
and velocity with the settings of the components the solver is built
from (Physics, Joint, its collider, SoftBody, CollisionGroup,
PlaneHold: every component declaring simulation = "physics").
Stepping N steps
after a restore reaches the state N steps after the snapshot reached,
bit for bit
(Physics.stateDigest reads the same digest), however many times it is
restored: a bridge builder tests a bridge and resets it, a crash test
retries from the moment before impact, a puzzle undoes a move.
snapshot:size() is the bytes it is saved as, snapshot:info() what it
holds and how long it took, snapshot:save(path) writes it to the VFS for
Physics.loadSnapshot. A snapshot lives in memory until nothing holds it
or snapshot:release(); live snapshots together hold at most 1 GiB. The
physics guide's "Snapshots" section states what it costs.
Returns PhysicsSnapshot — The snapshot.
local before = Physics.snapshot(); print(before:size(), before:info().bodies)
local s = Physics.snapshot(); Physics.advance(120); Physics.restore(s)
globals/physics/softBodyEnergy
physics.softBodyEnergy(softId: string | entityRef, opts: { mark: boolean? }?) -> PhysicsSoftBodyEnergy?
Read a soft body's energy ledger, to tune a deformable by numbers:
the kinetic and elastic energy it holds now, and since the mark the work
gravity did on it, the work plastic flow absorbed, the energy tears and
cuts took out of it, what pieces split off carried away and what it lost
otherwise (damping, friction, contacts, less what whatever holds or
pushes it gave it), each by region too, with the peak acceleration of
its centre of mass.
opts.mark = true sets the mark first and starts the ledger again; a body
never marked reads its kinetic and elastic energy only (accounted is
false), and costs nothing per step. A marked body is accounted after
every step that moves it, so a crash read straight after it reads the
whole crash: mark before, read after.
Parameters
softIdstring | entityRef— The soft body's entity.opts{ mark: boolean? }(optional) —{ mark: boolean? }.
Returns PhysicsSoftBodyEnergy? — A PhysicsSoftBodyEnergy ledger, or nil when nothing in the scene answers to that id.
Physics.softBodyEnergy(shell, { mark = true }) -- before the crash
local e = Physics.softBodyEnergy(shell); print(e.absorbed, e.elastic, e.dissipated) -- after it: joules
for _, r in Physics.softBodyEnergy(shell).regions do print(r.name, r.absorbed) end
globals/physics/softBodySettings
physics.softBodySettings(changes: table?) -> PhysicsSoftBodySettings
The settings every soft body of the world is simulated under, and the
way to change them: how many extra substeps a second a hard hit may add, how stiff
soft contacts are, which tangle and overlap recovery runs, and how far
the FEM solver (SoftBody.solver = "fem") solves each step. Each one
trades simulation quality for cost; Physics.stepCost().softBodies shows
what each body costs under them. They are world settings
(physics.soft_body_* in .world_settings) saved with the world: a
change reads back at once and the solver runs under it from the next
physics tick. Written during play, they land on the play shadow like any
other /source write: the solver runs under them at once, and they are
gone when the play edits are discarded. Write them in edit mode (or keep
them with vfs.promotePlayShadow("/zero/source/.world_settings")) for the
world to keep them.
Parameters
changestable(optional) — OptionalPhysicsSoftBodySettingsfields to change; the fields left out keep their values. A field the settings do not have, or a value of the wrong type or out of range, is refused by name.
Returns PhysicsSoftBodySettings — The settings with changes applied: what the next tick runs under.
print(Physics.softBodySettings().maxExtraSubstepRate)
Physics.softBodySettings({ maxExtraSubstepRate = 60 }) -- cheaper hard hits
Physics.softBodySettings({ tangleDetection = false, overlapConstraints = false })
Physics.softBodySettings({ femMaxIterations = 60 }) -- FEM bodies converge further each substep
globals/physics/softBodyState
physics.softBodyState(entityId: string | entityRef, opts: table?) -> PhysicsSoftBodyState?
What the solver holds for one soft body (an entity with a SoftBody
component): its particle, cell and edge counts, the volume it encloses
against its rest volume, its centre of mass and frame, the box around its
particles, how fast they move, whether it sleeps, and what it touches,
and in render how the entity's model is drawn carried by the body.
plastic is how deep the deformation that stayed is, in metres (a dent
past the component's plasticYield; plasticMean the mean over the
particles), 0 for a body that only deformed elastically.
diverged is true while a step has carried the body into a state no
material reaches (its particles spread, or its volume grown, past ten
times the shape it is held at, or a particle carried to a value that is
not a number), and divergence says what was measured; the engine log
names the body the step it diverges.
tearStrain and tearForce are the thresholds it tears past (0 tears
never), and piece names the torn piece a body split off another
continues (nil for a body built from its fields).
attachments lists the regions held to rigid bodies (attachSoftRegion)
with the force each pulls with, attachedParticles counts the particles
tied, and clusters counts the body's frame plus one per joint end
anchored on a region of it. pins lists the regions pinned
(pinSoftRegion) with how many particles each holds, its target and
where its particles' centre stands, and pinnedParticles counts the
particles held kinematic. diagnostics is what the physics debug views
picture of the body as numbers: inverted cells, self-crossings, element
loads (maxLoad, loadedElements), pinned and attached particles (see
PhysicsSoftBodyDiagnostics; Physics.debugLines draws them).
replication, on a synced entity in a multiplayer session, says which
peer simulates the body (authority "local" or "remote", owner)
and what it costs on the wire here (lastSync in seconds,
bytesPerSecond).
stability compares the body's stiffest elements with the rate the
solver runs them at, from the moment it is built, before it steps (see
PhysicsSoftBodyStability): holds is false and cannotHold names each
part, with its frequency and the substep rate, when the default solver
holds it softer than it is stated.
status says where the body stands: "built", "pending" (the
component stands and the body is not built yet, waitingFor naming what
the build waits on), "refused" (refusal says why the component was
not built) or "none" (no SoftBody component). A body is built at the
start of the frame after its component is added, so a read in the call
that added it answers "pending"; wait on status rather than reading
exists = false as a refusal. Answers in edit mode as well as play mode.
Parameters
entityIdstring | entityRef— Entity id or proxy.optstable(optional) —{ positions: boolean?, contactPoints: boolean?, contactsWith: (string | entityRef)? }:positions = trueadds every particle's world position;contactPoints = trueadds each contact's individual points (each contact names its count, normal, depth, impulse and particles either way);contactsWithreports only the contacts with that one entity, so a read about one pair costs that pair alone.
Returns PhysicsSoftBodyState? — A PhysicsSoftBodyState, or nil when nothing in the scene answers to that id.
local s = Physics.softBodyState(jelly); print(s.particleCount, s.volumeRatio, s.sleeping)
print(Physics.softBodyState(shell).plastic) -- metres of dent the shell kept
local s = Physics.softBodyState(shell); if s.diverged then print(s.divergence) end
for _, p in Physics.softBodyState(jelly, { positions = true }).positions do print(p.y) end
local r = Physics.softBodyState(jelly).render; print(r.drawn, r.vertexCount, r.uploadedThisFrame)
local s = Physics.softBodyState(jelly); if s.status == "pending" then print("waiting for", s.waitingFor) end
local st = Physics.softBodyState(beam).stability; if not st.holds then print(st.cannotHold[1]) end
globals/physics/softBodyTears
physics.softBodyTears() -> { PhysicsSoftBodyTear }
Every soft body tear since the last call to this function, oldest
first, with the entities of the pieces each split off: the same records
onSoftBodyTear delivers. The 256 most recent are kept.
Returns { PhysicsSoftBodyTear } — Array of PhysicsSoftBodyTear.
for _, t in Physics.softBodyTears() do print(t.kind, t.entity, #t.pieces) end
globals/physics/softElements
physics.softElements(softId: string | entityRef) -> PhysicsSoftElements?
Read every element of a soft body in one call: the force each carries
(newtons, positive pulling, negative pushing), its strain, length, rest
length, permanent set, its load against its break limit, whether it
broke, and where its two ends stand in world space (endA, endB; a
broken element's are where its particles went), as arrays indexed by
element. A custom body's authored elements read by their number in
the component's list, wherever a tear left them, the same read from the
body's entity and from each piece's; any other body's edges
read in its own order with a / b naming their particles. The way to
colour a structure by stress, draw its members, find its most loaded
member or watch a span carry a load, at the cost of one call per frame.
Parameters
softIdstring | entityRef— The soft body's entity.
Returns PhysicsSoftElements? — A PhysicsSoftElements report, or nil when nothing in the scene answers to that id.
local s = Physics.softElements(bridge); for i = 1, s.count do if s.load[i] > 0.8 then print("member", i, "near breaking", s.force[i]) end end
local s = Physics.softElements(bridge); for i = 1, s.count do if not s.broken[i] then print("member", i, "from", s.endA[i], "to", s.endB[i]) end end
globals/physics/softParticles
physics.softParticles(softId: string | entityRef, region: PhysicsSoftRegion?) -> PhysicsSoftParticles?
Read the particles of a soft body that a region selects: where each
stands, how fast it moves, where it stands in the body's rest shape and
whether it is pinned, with the selection's centre of mass and mean
velocity. Physics.setSoftParticles writes a read back as it is. The way to see a dent where a hit
landed, how far a pinned corner was dragged, or how a region moves.
indices name the particles for comparing two reads of the same body.
The region is resolved at each call 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 moved can select other particles than an earlier
read of the same region; a pin's own particles read back through
Physics.softBodyState(softId).pins (center) and the pinned flags.
Parameters
softIdstring | entityRef— The soft body's entity.regionPhysicsSoftRegion(optional) — Which particles to read, asPhysics.softRegiontakes it; nil reads the whole body.
Returns PhysicsSoftParticles? — A PhysicsSoftParticles report (exists, count, indices from 0, world positions, velocities and restPositions, pinned, center, meanVelocity, refusal), or nil when nothing in the scene answers to that id.
local top = Physics.softParticles(jelly, { box = { min = {-0.5, 0.4, -0.5}, max = {0.5, 0.5, 0.5} } }); print(top.count, top.center.y)
local near = Physics.softParticles(shell, { box = { min = {1.6, 0, -0.3}, max = {2.2, 1, 0.3} }, space = "world" })
globals/physics/softRegion
physics.softRegion(region: PhysicsSoftRegion?) -> { [string]: any }
The engine form of a soft body region: the record the SoftBody
component's attachments and a Joint's soft body ends carry. A region
names part of a 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, and nil (or {}) the whole body.
Coordinates are in the soft body entity's local space, the unit box it
is built in (-0.5 to 0.5 on each axis, before its scale; for a custom
body, the space its particles are listed in), so a region
stays the same part of the body wherever the body is; space = "world"
reads them in world space instead. A box counts a particle whose contact
skin reaches into it: a generated body's outer particles stand that skin
inside the unit box, so a box flat on one of its faces
(min = {-0.5, -1, -1}, max = {-0.5, 1, 1}) holds that face's particles.
Errors naming the key that is wrong.
Parameters
regionPhysicsSoftRegion(optional) —{ box = { min = v, max = v } | { v, v }, nearest = v, space = "local" | "world" }, or nil for the whole body.
Returns { [string]: any } — { kind = "Whole" | "Box" | "Nearest", min, max, point, world }.
Physics.softRegion({ box = { min = {-0.5, 0.45, -0.5}, max = {0.5, 0.5, 0.5} } })
Physics.softRegion({ nearest = {0, 0.5, 0} })
globals/physics/solveIk
physics.solveIk(endEffector: string | entityRef, target: any?, opts: table?) -> table
Solve an articulation's joints for one of its links to reach a
target: inverse kinematics by damped least squares over the joints'
coordinates, each joint's travel or single angle held inside its range and
each angle with no range turned at most half a turn from where it stands. By
default the links are put where the solve found; with apply = false it
only answers, and each joint's found position is the motorTarget a
position motor drives the arm there with (degrees for an angle).
Parameters
endEffectorstring | entityRef— The link that reaches (an entity whose body is a link below the root).targetany(optional) — Where it reaches: a point{x, y, z}in world space.optstable(optional) — Optional:offset(the point of the link that reaches, in its own frame; its origin by default),rotation({x, y, z, w}or an entity'srotation, the turn the link is to stand at as well),from(the link whose joint, with every joint below it, moves; every joint from the root's children down by default),iterations(default 50),damping(default 0.1; larger is steadier near a stretched-out pose),tolerance(metres, and radians forrotation; default 0.001),apply(default true).
Returns table — { reached, error, angleError, iterations, joints }: reached when the point stands within tolerance of the target, error its distance in metres, angleError the degrees from rotation (0 when none was asked), and joints each moved joint from the top down as { entityId, angle?, offset?, axes }: angle (degrees) for a joint whose one free axis is an angle, offset (metres) for one whose one free axis is a travel, and axes.<linX..angZ> the same per free axis (a ball joint's three angles read none). A target out of reach answers reached = false with the arm stretched toward it.
local r = Physics.solveIk(hand, { 1.2, 0.8, 0 }); print(r.reached, r.error)
local r = Physics.solveIk(gripper, cup.position, { apply = false }); for _, j in r.joints do entity(j.entityId).component.get("Joint").motorTarget = j.angle end
globals/physics/solverSettings
physics.solverSettings(changes: table?) -> PhysicsSolverSettings
The settings the constraint solver runs every step of the world under,
and the way to change them: the tick rate, how much simulated time a
frame may catch up and how many of its steps run whatever they cost,
the substeps each step is divided into, the passes within
a substep, how much of its last impulse a contact (and, with joint warm
starting, a joint) starts from, how stiff and how damped contacts are,
the solver's tolerances and their length unit, continuous collision's
substeps and the friction model. Each field is the world
setting physics.<name> (physics.solver_iterations,
physics.pgs_iterations, ...) saved with the world in
.world_settings; PhysicsSolverSettings states each one's default and
range, and the physics guide's "Tuning the solver" what each changes. A
change reads back at once and the solver runs under it from the next
physics step, with no restart; Physics.worldState().solverSettings
reads what the solver holds. Written during play, they land on the play
shadow like any other /source write: the solver runs under them at once,
and they are gone when the play edits are discarded. Write them in edit
mode (or keep them with vfs.promotePlayShadow("/zero/source/.world_settings"))
for the world to keep them.
Parameters
changestable(optional) — OptionalPhysicsSolverSettingsfields to change; the fields left out keep their values. A field the settings do not have, or a value of the wrong type or out of range, is refused by name.solverIterationsalso takes"auto", the default: enough substeps for 120 solves a second at the tick rate (and at least 2), worked out again whenever the tick rate changes. A count equal to the one the tick rate works out to is saved as"auto", so the settings read and written back unchanged keep the count following the tick rate.
Returns PhysicsSolverSettings — The settings with changes applied: what the next step runs under.
print(Physics.solverSettings().solverIterations)
Physics.solverSettings({ tickRate = 60, solverIterations = 8 }) -- a long bridge or chain
Physics.solverSettings({ solverIterations = "auto" }) -- substeps follow the tick rate again
Physics.solverSettings({ lengthUnit = 100 }) -- a world built in centimetres
Physics.solverSettings({ contactFrequency = 15 }) -- softer, squashier contacts
Physics.solverSettings({ tickRate = 240, maxCatchUpSeconds = 0.1 }) -- a frame catches up at most 0.1 s
globals/physics/sphereCast
physics.sphereCast(origin: vec3, radius: number, direction: vec3, maxDistance: number?, exclude: (string | {string})?, options: PhysicsCastOptions?) -> PhysicsHit?
Cast a sphere along a direction and return the first hit.
A trigger (isTrigger) holds nothing up, so the sweep passes through it.
Many casts a frame: Physics.castMany answers them all in one call.
Parameters
originvec3— Sphere center at the start of the cast.radiusnumber— Sphere radius.directionvec3— Cast direction, of any length: the engine normalises it, somaxDistanceanddistanceare world units.maxDistancenumber(optional) — Optional distance limit.exclude(string | {string})(optional) — Optional entity id, or array of entity ids, to exclude from hits. Applied while sweeping rather than to the answer, so a cast that starts inside an excluded collider reports what is behind it.optionsPhysicsCastOptions(optional) — OptionalPhysicsCastOptions:{ mover = entity }casts for the entity the cast moves (a character controller, or anything moved by casts), so it meets colliders as that entity's body does: a one-way collider (oneWay) answers only on the face its direction points out of, to a cast that starts outside it; a collider whosecontactTagthe contact filter answers "ignore" or "sensor" with a tag of the mover's own colliders is passed; and the one-way collidersPhysics.passThrough(mover)drops the mover through are passed until it is clear of them.
Returns PhysicsHit? — Hit table { entityId, body, bodyType, point, normal, distance, startedInside, softBody?, surface?, surfaceVelocity? }, or nil if nothing hit. body is the id of the entity standing for the body the collider belongs to: the body's own entity when the collider was authored on a child entity (a part of a vehicle or an assembled prop, which composes onto its ancestor's body), and the collider's own entity for static world geometry that rides no body, such as the ground. bodyType is that body's kind ("dynamic", "static", "kinematic", "kinematicVelocity" or "soft"; "static" for static world geometry). The push verbs take body and entityId alike. startedInside is false for a surface the query crossed on its way there, and true when the query's own start already lay inside that collider — where distance is 0, point is the start itself, and normal is the shortest way out of the collider. normal is a unit vector either way. surface names the surface the collider is made of where the query met it (Physics.defineSurface; on a heightfield whose samples name layers, the layer of the sample nearest the point), and is absent for a collider naming none. surfaceVelocity is the collider's surfaceVelocity in world space (m/s), the motion its surface carries what stands on it with, and is absent for a collider whose surface holds still. softBody is set when what was hit is a soft body, whose surface the query meets as it is deformed now: a PhysicsSoftHit naming the surface triangle, the particles carrying it with the hit's weight on each, the particle nearest the hit, and region, the hit as a soft region to hand to Physics.applyImpulse, Physics.pinSoftRegion or Physics.softParticles. Physics.applyImpulseAtPoint takes the hit's point as it is.
local hit = Physics.sphereCast(o, 0.5, dir, 10)
local hit = Physics.sphereCast(o, 0.5, dir, 10, selfId)
globals/physics/stateDigest
physics.stateDigest(opts: table?) -> PhysicsStateDigest
Take a digest of the physics simulation's state as it stands: one hash,
sixteen hex digits, over every rigid body's type, pose, velocities and
sleep state, every joint's carried impulses and every soft body's
particles. Two engines whose digests are equal hold the same state, so a
native and a browser player, two peers on one world or two runs of one
scripted scene check they agree by comparing digests instead of every
pose. Read it from Physics.onAfterStep for the state each step left, or
any time on demand. The digest depends on the state alone and is the
same on every platform for the same state. Two runs of one scene reach
the same state when they run the same script with the same inputs on the
same steps: in two freshly started engines (native or browser), and in
one engine that despawned the first run before building the second (a
level restarted in the same session, or in a new play session),
whatever else that engine built and removed before. The physics guide's
"State digests and determinism" section states every condition and what
was measured.
Parameters
optstable(optional) —{ quantum?, key?, entities?, entries?, values? }.entities, an array of entity ids, covers only those entities' bodies, joints and soft bodies (every entity by default), so a game hashes its own simulation apart from the rest of the world.quantum(0, the exact bits, by default) rounds each value to that step before hashing, so two states within it read alike.keynames each entry by the entity's"id"(default; engines on one world share ids) or its"name"(engines that each spawned the same scene share names).entries = truelists each body, joint and soft body with its own digest;values = trueadds the numbers each was hashed from, whichPhysics.firstDivergencenames a difference by.
Returns PhysicsStateDigest — A PhysicsStateDigest: digest, step, the counts, and entries when asked.
local d = Physics.stateDigest(); print(d.step, d.digest)
local d = Physics.stateDigest({ key = "name", values = true }); print(#(d.entries :: any))
globals/physics/stepCost
physics.stepCost() -> PhysicsStepCost?
What the last physics step cost, stage by stage — the same figures
worldState().step carries, for a caller that wants only these. Each
covers that one step rather than a window of them, and consecutive steps
over the same resting scene vary by tens of percent, so several samples
averaged is the honest read of what a step costs. softBodyMs is the
soft body part of the step and softBodies each soft body's part of it.
A frame can run several steps; recent lists the last 64 with their
ordinals (step), so a loop reading once a frame counts every step.
Physics.catchUp() states how many frames dropped simulated time
catching up and how much.
Returns PhysicsStepCost? — A PhysicsStepCost, or nil on a frame where the pipeline did not step — a paused simulation, or a world still bootstrapping.
local c = Physics.stepCost(); if c then print(c.stepMs, c.narrowPhaseMs) end
local c = Physics.stepCost(); if c then for _, b in c.softBodies do print(b.entity, b.ms, b.particles) end end
local seen, total = 0, 0
-- once a frame: every step since the last read, however many a frame ran
local c = Physics.stepCost(); if c then for _, s in c.recent do if s.step > seen then total += s.softBodyMs; seen = s.step end end end
globals/physics/stillnessReasons
physics.stillnessReasons() -> { string }
Every reason whyStill can answer with, in the order the engine
considers them. Read from the engine, so the list is the one the answers
come from.
Returns { string } — An array of reason names.
for _, reason in Physics.stillnessReasons() do print(reason) end
globals/physics/surfaces
physics.surfaces() -> { [string]: PhysicsSurface }
Every surface Physics.defineSurface defined, by name.
Returns { [string]: PhysicsSurface }.
for name, s in Physics.surfaces() do print(name, s.friction, s.rollingResistance) end
globals/physics/tearSoftBody
physics.tearSoftBody(softId: string | entityRef, region: PhysicsSoftRegion)
Tear a soft body at a region: every edge and cell holding a particle of
the region comes apart there, opening a hole or, when the region runs
across the body, splitting it. Applied straight after the next physics
step; a piece the tear separates becomes an entity of its own (see
onSoftBodyTear), and it reports as a tear of kind "tear". Raises when the
entity carries no SoftBody, for a region naming no box and no point (the
whole body), and in edit mode, where nothing simulates.
Parameters
softIdstring | entityRef— The soft body's entity.regionPhysicsSoftRegion— Which particles to tear through, asPhysics.softRegiontakes it:{ box = { min, max } }or{ nearest = point }in the entity's unit box (-0.5 to 0.5 on each axis),space = "world"for world coordinates.
Physics.tearSoftBody(cloth, { nearest = hit.point, space = "world" })
Physics.tearSoftBody(sheet, { box = { min = {-0.02, -1, -0.5}, max = {0.02, 1, 0.5} } })
globals/physics/touching
physics.touching(entityId: string | entityRef, otherId: string | entityRef) -> (boolean, number, { PhysicsContactPoint })
Whether two entities are touching, and how deeply.
Parameters
entityIdstring | entityRef— Entity id or proxy.otherIdstring | entityRef— The other entity id or proxy.
Returns (boolean, number, { PhysicsContactPoint }) — (touching, deepestPenetration, points) — deepestPenetration is in metres and 0 for surfaces that meet without overlapping.
local hit, depth = Physics.touching(a, b); print(hit, depth)
globals/physics/tyreCurve
physics.tyreCurve(entityId: string | entityRef, opts: table?) -> table?
Measure a wheel's tyre grip curve: the force its tyre pushes with at a steady slip, swept over slip ratio (along the road), slip angle (across it) and load, as the wheel's WheelCollider fields state its grip and as its solve settles on at that slip. Tune a tyre by numbers: its peak, where it peaks, how far it falls past the peak, and how its grip per newton falls with load.
Parameters
entityIdstring | entityRef— The wheel entity (it carries the WheelCollider).optstable(optional) — Optional{ loads = { N... }?, slipRatios = { ... }?, slipAngles = { degrees... }?, at = { { slipRatio, slipAngle }... }?, surface = string? }: the loads to sweep (default the load the wheel carries now, or itsreferenceLoad), the slip ratios (default 0 to 1 by 0.025), the slip angles (default 0 to 30 degrees by 1), pairs of slips to answer together, and the surface the tyre grips (default the one it touches now; a surfacePhysics.defineSurfacedefined scales every peak and the combined limit by itsfriction).
Returns table? — { entity, spins, surface?, surfaceGrip, loads = { { load, gripScale, side, forward? } }, at? }, or nil if the entity carries no WheelCollider. surface names the surface the curve is on and surfaceGrip the share of its stated grip the tyre grips it with (its friction when defined, else 1). side is { slipAngles, forces, perLoad, peak = { slipAngle, force, perLoad }, slide = { slipAngle, force, perLoad } } (forces in newtons, perLoad each over the load, peak the curve's peak, at the slip its grip peaks at, slide the force at the sweep's widest slip); forward is the same against slipRatios, present for a wheel that spins on its own (spins, an inertia above 0); gripScale is the share of its stated grip the tyre has per newton at that load (loadSensitivity); at lists { slipRatio, slipAngle, forward, side, grip } for each pair, at the first load.
local curve = Physics.tyreCurve(wheel.id); print(curve.loads[1].side.peak.slipAngle, curve.loads[1].side.peak.perLoad)
globals/physics/upAt
physics.upAt(point: vec3, groups: number?, into: { [string]: any }?) -> vec3
Up at a point: the unit direction against the gravity there
(Physics.gravityAt). The way a character stands on a small planet, a
camera keeps level and a walker's feet point away from. Where no gravity
acts at all it is up against the world's gravity vector, and +Y where
that is zero too.
Parameters
pointvec3— The point, in world space.groupsnumber(optional) — The collision membership of the body asking, as a bitmask. Default: every group.into{ [string]: any }(optional) — A table to write the answer'sx,yandzinto and return: a script reading this every frame into one table allocates nothing. A new table when left out.
Returns vec3 — The unit up direction there (into when given).
local up = Physics.upAt(entity(player).position)
globals/physics/vehicleState
physics.vehicleState(chassisId: string | entityRef) -> PhysicsVehicleState?
Read a vehicle: the chassis body's forward speed and the state of every wheel under it (the wheels whose nearest rigid-body ancestor is this chassis), and the wheels that came off it.
Parameters
chassisIdstring | entityRef— The chassis entity (the rigid body the wheels sit under).
Returns PhysicsVehicleState? — PhysicsVehicleState: { speed, groundedWheels, wheels, detachedWheels }, or nil when the chassis has no WheelCollider under it. speed is metres per second along the chassis' forward (-Z), negative in reverse; groundedWheels is how many of wheels touch the ground; wheels lists getWheelState tables of the wheels on the vehicle, each with its entityId, in the order the vehicle steps them, which is the order the wheels arrived in the world (the first spawned first), the same on every run and every engine (a wheel that has not stepped yet comes after those, by name); detachedWheels lists the wheels that came off it the same way, in the order they held on it, each with its detachReason and detachLoad.
local car = Physics.vehicleState(carId); print(car.speed, car.groundedWheels)
globals/physics/wakeUp
physics.wakeUp(entityId: (string | entityRef)?)
Wake an entity's sleeping rigid or soft body so it resumes
simulating. The motion setters (applyImpulse, setVelocity,
setAngularVelocity) wake the body for you; call this to wake one
explicitly.
Parameters
entityId(string | entityRef)(optional) — Target entity id or proxy; resolves from script context when omitted.
Physics.wakeUp(id)
globals/physics/water
physics.water(point: vec3, moment: number?, body: string?) -> PhysicsWaterSample?
The water at a point: where the surface over it stands, which way the
surface faces and moves, how deep the point is, where the bottom is and
how the water there moves (PhysicsWaterSample), from every body of water
defined: a water kit's sea, a Terrain's lakes and rivers, a pool content
declared (Physics.defineWater). Nil where no water covers the point. It
reads the water at moment on the water clock (Physics.waterTime), by
default now: inside a physics step the moment that step reaches, so a
force applied from Physics.onBeforeStep reads the water of its own step,
and otherwise the frame's. Evaluated on the CPU from the definition the
water is drawn from, so the same point and moment answer the same on every
peer, at any rate a script calls it. body asks one body alone, whatever
else covers the point.
Parameters
pointvec3— The point, in world space.momentnumber(optional) — Seconds on the water clock. Default: now.bodystring(optional) — The name of the one body to answer for.
Returns PhysicsWaterSample?.
local w = Physics.water(entity(buoy).position); if w and w.submerged then Physics.applyForce(buoy, { 0, w.depth * 1000 * 9.81, 0 }) end
Physics.onBeforeStep(function() local w = Physics.water(entity(raft).position); if w and w.submerged then Physics.setVelocity(raft, w.velocity) end end)
globals/physics/waterEventsDropped
physics.waterEventsDropped() -> number
How many water entries and exits the engine let go before anything read them: its queue keeps 4096 between two deliveries. Zero when nothing was lost.
Returns number — The count since the world started.
if Physics.waterEventsDropped() > 0 then log.warn("water events dropped") end
globals/physics/waterMany
physics.waterMany(points: { vec3 }, moment: number?, body: string?) -> { PhysicsWaterSample | false }
Physics.water at each of points, all at one moment: a hull's
sample points in one call. A point no water covers answers false.
Parameters
points{ vec3 }— The points, in world space.momentnumber(optional) — Seconds on the water clock. Default: now.bodystring(optional) — The name of the one body to answer for.
Returns { PhysicsWaterSample | false } — One PhysicsWaterSample (or false) per point, in order.
for i, w in Physics.waterMany(hullPoints) do if w and w.submerged then lift += w.depth end end
globals/physics/waterTime
physics.waterTime() -> number
The water clock now: the seconds of simulation this engine has run.
It is the moment Physics.water reads at by default:
inside a physics step the moment that step reaches, otherwise 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), or the last
step's moment in a world that draws its bodies unblended
(physics.interpolation off), so a body floating on the water is drawn on
the surface drawn with it. Each step carries it on by the simulated
seconds it covers, so it stands still while the simulation is held (edit
mode, a paused play), follows engine.timeScale, drops the seconds of the
steps a slow frame drops, and Physics.advance carries it on by the steps
it runs: a sea drawn at it is the sea the steps float bodies on. In a
multiplayer session every peer reads one moment, to within the session
clock's accuracy (multiplayer.sessionClock): the session's time wrapped
at 8192 s, which the steps keep the clock on by gaining or losing up to a
tenth of each step's seconds; a peer entering play, coming out of a pause
or a stall of more than half a second rejoins it at its next step. A peer
with no session counts from 0. The clock wraps at 8192 s, so a 32-bit
float holds it to half a millisecond and a shader takes it as a float
uniform; the built-in sea's waves repeat over 8192 s and run on across
the wrap without a seam.
Returns number — Seconds on the water clock.
local ahead = Physics.water(p, Physics.waterTime() + 0.5)
globals/physics/waters
physics.waters() -> { [string]: any }
Every body of water defined, by name, with what it is: its kind,
priority, density, entity, space (with, for a body stated in its entity's
space, the frame the entity stands it at: position, rotation
{ x, y, z, w } and scale, or nowhere = true while the entity is
scaled to nothing along an axis), region, current, and for a sea its waves,
lattices, period, speed and shoalDepth, for a grid its columns,
rows, texels wet and whether its flow is stated or follows the
slope.
Returns { [string]: any } — { [string]: table }.
for name, w in Physics.waters() do print(name, w.kind) end
globals/physics/whyStill
physics.whyStill(entityId: string | entityRef) -> (string?, string?)
Why the solver is not moving a body. Returns nil when it IS moving
it, and otherwise one of noBody, simulationNotStepping, disabled,
static, kinematic, infiniteMass, translationLocked,
gravityDisabled, asleep, outsideIsland, resting, aboutToMove —
the nearest cause, so the answer names the thing to change. A second return
carries the detail: which collider it rests on and how deeply, what its
effective gravity works out to, and so on.
Parameters
entityIdstring | entityRef— Entity id or proxy.
Returns (string?, string?) — (reason, detail).
local why, detail = Physics.whyStill(id); if why then print(why, detail) end
globals/physics/wind
physics.wind(point: vec3, moment: number?) -> vec3
How the air at a point moves, m/s: every wind field covering it,
summed, at moment on the water clock (Physics.waterTime), by default
now (inside a physics step, the moment that step reaches). Zero where no
field blows. The same point and moment answer the same on every peer.
Parameters
pointvec3— The point, in world space.momentnumber(optional) — Seconds on the water clock. Default: now.
Returns vec3 — The wind's velocity.
local w = Physics.wind(entity(flag).position); print(w.x, w.z)
globals/physics/winds
physics.winds() -> { [string]: any }
Every wind field defined, by name: its kind, velocity, gust,
gustPeriod, gustSize, gustDirection, space, its region,
falloff and entity where it has them, the frame its entity stands
a field in that entity's space at (or nowhere = true), and what its
kind is made of (a grid's origin, size, columns, rows, layers,
scroll, wrap; a vortex's or radial wind's center, axis,
radius, speed, and a vortex's inflow, updraft and
updraftRadius).
Returns { [string]: any } — { [string]: table }.
for name, w in Physics.winds() do print(name, w.velocity.x) end
globals/physics/worldState
physics.worldState() -> PhysicsWorldState
How many bodies, colliders, joints and contacts the simulation holds
right now, with world gravity, the timestep, whether the pipeline is
stepping at all, what the last step cost, and how many step hooks run
around every step (stepHooks). Counted off the solver, so
a body that failed to build is absent here while its Physics component
still exists.
Returns PhysicsWorldState — A PhysicsWorldState.
local w = Physics.worldState(); print(w.bodies.awake .. "/" .. w.bodies.total .. " awake")
print(Physics.worldState().contacts.touchingPairs .. " pairs touching")