The simulation tick and physics¶
The server runs the world in ticks, 60 per second. Each tick runs one physics step of exactly 1/60 s, runs the scripts' Update callbacks, and sends the changes to clients. World.Clock reads the tick rate in TickRate and the current tick in Tick. Each client also steps its own physics world in 1/60 s steps, and a script call acts on the world of the side that makes it; Network authority and replication explains which side's changes win.
Choose Update or PhysicsUpdate¶
A script defines either callback as a global function, before its first wait such as task.wait or WaitFor. Both run in server and client scripts.
Update(dt)runs once per frame, after that frame's physics steps. Use it for game logic: timers, scores, spawning, and reading where parts ended up. On the server a frame is one tick anddtis always 1/60. On a client a frame is one drawn frame anddtis the real time since the last one.PhysicsUpdate(dt)runs before every physics step withdtset to 1/60. Use it to push parts with forces. On the server it runs once per tick. On a client it runs once for every whole 1/60 s that has passed, so a single drawn frame can run it zero, one or several times.
-- Server script in a part: turn 90 degrees a second.
function Update(dt: number)
local rot = self.Rotation
if rot then
self.Rotation = rot * Rotation.fromAxisAngle(Vector3.YAxis, 90 * dt)
end
end
-- Server script in a part: make it dynamic and cancel gravity so it floats.
local body = self.Body
if body then
body.Motion = "Dynamic"
end
function PhysicsUpdate(dt: number)
local b = self.Body
local mass = b and b.Mass
if b and mass then
b:ApplyForce(-mass * World.Gravity)
end
end
Order of one server tick¶
Before each tick the server reads the messages that arrived from clients. The tick then runs these stages in order:
- Scripts added or saved since the last tick load and run their top-level code.
- A character whose position is not a finite number is marked dead.
- Changes to
World.Gravityand to the collision rules set byPhysics.SetCollidesreach the physics world. - The physics step runs:
- Each player's next input becomes their character's movement.
- Systems in the
"PrePhysics"phase run. Touched,TouchEndedandHithandlers run for the contacts of the previous step.PhysicsUpdateruns, then systems in the"Physics"phase.- The simulation advances 1/60 s: transforms written by scripts reach the bodies, characters apply their movement forces, the solver moves every awake body, animations advance, and the results are written back to
Position,RotationandVelocity. - Systems in the
"PostPhysics"phase run.
- World positions are recomputed down the hierarchy, parents before children.
Nethandlers run once per message that arrived.- Systems in the
"PreUpdate"phase run, thenUpdate, then threads whosetask.waithas finished resume. - Systems in the
"Default"phase run, then tweens write their values, and the signals for players who joined fire. - Entities whose
Lifetimeran out are destroyed, deaths of characters marked dead are announced, and the server sends the tick's changes to clients.
A client runs the same physics step stages for its own world, then the Net handlers, the "PreUpdate" and "Default" systems and Update once per drawn frame. Player joins happen only on the server.
Two consequences follow from this order. Update sees the positions the physics step just produced. A value written in Update, such as a new Position or World.Gravity, reaches the physics world at the next tick's step.
Run code over many entities¶
To run the same code over many entities, register a system with Query:System instead of putting a script in each one. A system runs once per phase over its Query, and the engine refreshes the query before each run. The phase decides where in the tick it runs: "PreUpdate", "Default" (the default), "PrePhysics", "Physics" or "PostPhysics". Pass the name of another system as after to run after it in the same phase. Systems run in server and client scripts. Entity properties and components explains components, and Column explains the values a query returns.
-- Server script: lift every body that has the Balloon tag.
local Balloon = World.DefineComponent("Balloon")
local balloons = World.Query(Component.Body, Balloon)
balloons:System("LiftBalloons", function(q, dt: number)
local entities = q:Entities()
for i = 1, #q do
local body = entities[i].Body
local mass = body and body.Mass
if body and mass then
body:ApplyForce(-1.2 * mass * World.Gravity)
end
end
end, "Physics")
Push parts¶
These Body members act on a part whose Motion is "Dynamic":
ApplyForce(force, at?)pushes the part during the next physics step only. Calls in the same step add up, so a steady push needs a call every step, fromPhysicsUpdateor a"Physics"system.ApplyImpulse(impulse, at?)changes the velocity at once, by the impulse divided by the mass.ApplyTorque(torque)turns the part during the next physics step only, andApplyTorqueImpulse(impulse)changes the spin at once.Velocityon the entity sets the velocity directly.
The four Apply methods print a warning such as ApplyForce: entity has no dynamic body, ignored and do nothing on a static or kinematic part. Mass is nil while the body is not simulated, such as before its first physics step. A call in a client script acts on the client's own world; send a Net.ToServer message so the server pushes the part for everyone.
Move parts from a script¶
Writing Position or Rotation does not move the physics body right away. The body moves at the start of the next physics step, and until then reading the property returns the value just written. A dynamic part jumps to the new place, keeps its Velocity, and wakes up.
To make a moving platform, keep the part's Motion at "Static" and write its position every frame, or animate it with Tween. The engine works out the platform's motion from the successive positions, so it pushes the parts it touches, and a part resting on it wakes and falls when the platform moves out from under it.
-- Server script in a static part: slide back and forth.
local start = self.Position or Vector3.Zero
local t = 0
function Update(dt: number)
t += dt
self.Position = start + Vector3.new(10 * math.sin(t), 0, 0)
end
A static part with a Velocity stays in place and moves its surface instead, like a conveyor belt; see Velocity.
To move a part only where scripts put it, set its Motion to "Kinematic". Gravity and collisions no longer move it, each written position is reached over the next step while pushing other parts aside, and the part stops after any step without a new write.
Sleeping parts¶
A part at rest falls asleep, and the simulation skips it until something wakes it. A part falls asleep after every point on it has moved slower than 0.6 units per second for half a second. Parts that touch each other fall asleep together, and any one of them that keeps moving keeps the others awake.
A sleeping part wakes when a script pushes it with an Apply method, writes its Velocity or Position, or when a moving part or platform touches it. Body.Sleeping reports whether a part is asleep.
Find parts in space¶
Physics has spatial queries against collider shapes. Raycast returns the first surface hit along a ray and RaycastAll every hit. OverlapSphere, OverlapBox and OverlapCapsule return the entities inside a volume. Spherecast, Boxcast and Capsulecast sweep a shape and return the first contact, and their All forms return every contact, nearest first. Pass an out table to reuse it across calls, and pass QueryOptions to exclude or include entities or to test against a collision group.
-- Server script in a part: list the parts within 10 units.
local found: { Entity } = {}
function Update(dt: number)
local pos = self.Position
if not pos then
return
end
table.clear(found)
Physics.OverlapSphere(pos, 10, { Exclude = { self } }, found)
for _, entity in found do
print(entity.Name)
end
end
Queries test the bodies as the last physics step left them, so a part moved by a script during this tick is still found at its old place. Queries follow the rules set by SetCollides only when the options name a CollisionGroup.
Limits¶
- One run of a script, until it yields or returns, may make at most 1,000,000 loop iterations and calls. Past that it stops with
script exceeded its instruction budget. - The server's scripts share one 256 MiB Luau heap, and so do one player's client scripts.
- An error ends only the call that raised it. After 5 consecutive runs over the instruction or memory budget, the engine stops the script's
Update,PhysicsUpdateand systems until the script is saved again. Engine errors lists the messages. - No body moves faster than 10,000 units per second; forces, impulses and
Velocitywrites stop at that speed.
Measure frame cost¶
Profiler.Frame() returns a FrameStats table for the last frame, with times in seconds for scripts, physics, networking and drawing, and the size of the Luau heap. Profiler.Scripts() returns a ScriptCost for each recently run script, with the smoothed time per frame of its Update, PhysicsUpdate and systems, and Profiler.Systems() does the same for each system. To time one block of code, wrap it in Profiler.Scope and read the result from Profiler.Scopes().
-- Server script: warn about slow ticks.
function Update(dt: number)
local stats = Profiler.Frame()
if stats and stats.Interval > 0.05 then
local scripts = math.round(stats.Script * 1000)
local physics = math.round(stats.Physics * 1000)
warn(`slow tick: {scripts} ms scripts, {physics} ms physics`)
end
end
How it works¶
Every physics step lasts exactly 1/60 s on the server and on clients, whatever the frame rate, so a force has the same effect at any frame rate. The server starts a tick every 1/60 s. When a tick runs long, the next ticks start immediately to catch up; when the server falls more than 8 ticks behind, it drops the missing time, so the world runs slower than real time. A client adds the time of each drawn frame to a counter, sped up or slowed by a few percent to keep its input in step with the server, and runs one step for every whole 1/60 s in it.
Inside each step the solver divides the 1/60 s into 4 substeps, so stacked parts and joints are solved four times per step.