Lua ScriptingAdvanced

Vehicles, constraints, ragdolls, and navigation

Drive wheeled and tracked vehicles, ride a body along a path, operate constraint motors, build ragdolls, move navigation agents, and follow a generated track's centreline.

Wheeled vehicles

setDriverInput(forward,right,brake,handBrake) accepts normalized inputs. Positive right steers right at the Lua API boundary. Separate setters are also available: setForwardInput, setRightInput, setBrakeInput, and setHandBrakeInput.

Read state with getVehicleForwardSpeed(), getVehicleRPM(), getVehicleGear(), isWheelInContact(index), and getWheelContactNormal(index). Wheel indices are zero-based and are rejected outside the vehicle's own wheel count.

Steering limit, engine torque, and brake torque are authoring-time fields on the vehicle object, not runtime calls. They are constraint construction parameters, so the physics engine has to rebuild the vehicle constraint to change one: set them on the object and reload the scene. Earlier versions exposed setMaxSteerAngle, setEngineTorque, and setMaxBrakeTorque from Lua. Those calls never took effect and have been removed.

Steering feel

setDriverInput applies the steering you hand it immediately and in full, so a driving script needs two things on top of the raw axis. Without them a car is unpleasant on a touch stick and dangerous at speed.

Ease the steering angle toward the axis; never assign it. Roughly a fifth of a second of lag is enough. Nothing about a thumb holds an exact heading, and a steering angle that tracks one exactly transmits every tremor to the wheels — the car weaves the whole way down a straight the player is holding straight. Read input.moveAxisX rather than input.moveLeft and input.moveRight: the booleans carry no magnitude, so a script built on them can only ask for full lock or nothing.

Scale the available lock down as getVehicleForwardSpeed() rises. Full lock at speed rolls a car over with no collision involved. Tire friction peaks at 1.8, so a chassis whose centre of mass sits higher above the contact patches than half its track width generates more lateral force than it takes to tip itself.

That second failure is also fixable on the object. A vehicle's Center of Mass Y Offset lowers the centre of mass in the chassis's local space, and the built-in presets put it at the bottom of the chassis box — what Jolt's own vehicle sample does. Raise it toward zero for a deliberately tippy vehicle.

local STEER_RATE, RETURN_RATE = 6.0, 10.0
local FULL_LOCK_SPEED, MIN_LOCK_SPEED, HIGH_SPEED_LOCK = 8.0, 30.0, 0.35
local steer = 0

function update(dt)
    local target = input.moveAxisX
    local speed = math.abs(gameObject.getVehicleForwardSpeed() or 0)
    local fade = (speed - FULL_LOCK_SPEED) / (MIN_LOCK_SPEED - FULL_LOCK_SPEED)
    fade = math.min(1, math.max(0, fade))
    target = target * (1 - fade * (1 - HIGH_SPEED_LOCK))

    -- Straightening out is quicker than turning in, so a correction reads as a
    -- correction rather than as the start of the opposite turn.
    local rate = STEER_RATE
    if math.abs(target) < math.abs(steer) then rate = RETURN_RATE end
    steer = steer + (target - steer) * (1 - math.exp(-rate * dt))

    gameObject.setDriverInput(input.moveAxisY, steer, 0, input.jump and 1 or 0)
end

The driving script vehicles_create_wheeled attaches to a new vehicle is written this way. The same reasoning applies to a tracked hull, which slews hard the instant a thumb drifts off centre. Through MCP, both creators save that script as an ordinary project script and return its id as script_id; scripts_list finds it by that id (with detail: "full" for the source), and either creator takes a script of your own instead of the stock one.

One-stick point-and-go driving

On a phone, a stick for steering plus Gas and Brake buttons is a lot of thumbs. The alternative is to treat the stick as a direction: push it the way you want the car to go, as seen on screen, and the car turns to face that way and drives, with how far you push as the throttle. Pull it toward the camera and the car turns round rather than reversing. The same script drives from the keyboard and a gamepad's left stick.

The stick becomes a world direction relative to the active camera — or, in a multiplayer room, to input.aimYaw, because the room server has no camera of the player's. The car then steers toward that direction, eased and with less lock at speed exactly as above. The sign is the easy thing to get backwards: a negative heading error is to the car's right, and positive right steers right.

local MAX_STEER_ANGLE = math.rad(35) -- heading error that means full lock
local steer = 0

-- Where the stick points, as a horizontal world direction, and how far.
local function stickTarget()
    local x, y = input.moveAxisX, input.moveAxisY
    local push = math.min(1, math.sqrt(x * x + y * y))
    if push < 0.1 then return nil, 0 end
    local f
    if input.aimYaw then
        f = { x = math.sin(input.aimYaw), z = math.cos(input.aimYaw) }
    else
        local camera = scene.getActiveCamera()
        f = camera and camera.getForward() or gameObject.getForward()
    end
    local length = math.sqrt(f.x * f.x + f.z * f.z)
    if length < 1e-6 then return nil, 0 end
    f = { x = f.x / length, z = f.z / length }
    -- Screen right is (-f.z, f.x): -X for a camera facing +Z.
    return { x = f.x * y - f.z * x, z = f.z * y + f.x * x }, push
end

function update(dt)
    local target, push = stickTarget()
    if not target then
        -- Let go: straighten up and come to rest.
        steer = steer * math.max(0, 1 - dt / 0.2)
        gameObject.setDriverInput(0, steer, 0.3, 0)
        return
    end
    local c = gameObject.getForward()
    local heading = math.atan(c.z * target.x - c.x * target.z,
                              c.x * target.x + c.z * target.z)
    local speed = math.abs(gameObject.getVehicleForwardSpeed() or 0)
    local wanted = math.max(-1, math.min(1, -heading / MAX_STEER_ANGLE)) / (1 + speed / 25)
    steer = steer + (wanted - steer) * math.min(1, dt / 0.2)
    -- Keep some drive through a turn-round so the car circles instead of stopping.
    gameObject.setDriverInput(push * math.max(0.35, math.cos(heading)), steer, 0, 0)
end

With this script the scene's touch controls need only a movement stick. For a gamepad player who prefers triggers, bind a gas action to the right trigger and brake to the left, and read their pull from input.actionValues — see Gamepad.

Skid marks and tyre tracks

startTrail({ offset = { wheel = i } }) lays a trail at wheel i's contact with the ground (zero-based, as for isWheelInContact), on a wheeled or a tracked vehicle. A wheel trail lies flat on the road by default, is as wide as the tyre, and pauses by itself while that wheel is in the air, so a jump leaves a gap rather than a streak. The other options are on the gameObject API reference. The bundled lua/vehicle_skid_marks.lua starts a paused trail on every wheel and lays marks while the car slides sideways, with a little hysteresis so a mark does not flicker. Put it on the car, or on another object with a vehicle object_ref variable pointing at the car, which is how to add marks to a car that already has a driving script. Condensed:

local car, trails, skidding = nil, {}, false
local SLIP = 2.5 -- sideways metres per second

function init()
  car = gameObject.getVar("vehicle") or gameObject
  for wheel = 0, 3 do
    local trail = car.startTrail({
      offset = { wheel = wheel },
      color = { r = 0.05, g = 0.05, b = 0.05 },
      opacity = 0.7, lifetime = 8, minDistance = 0.15, maxSegments = 256,
      emitting = false,
    })
    if trail then trails[#trails + 1] = trail end
  end
end

function update(deltaTime)
  if not car then return end
  local v, right = car.getLinearVelocity(), car.getRight()
  local slip = math.abs(v.x * right.x + v.y * right.y + v.z * right.z)
  -- Stop below 70% of the threshold, so a slide hovering at it is one mark.
  local now = slip > (skidding and SLIP * 0.7 or SLIP)
  if now ~= skidding then
    skidding = now
    for _, trail in ipairs(trails) do trail.setEmitting(skidding) end
  end
end

In a multiplayer room a player's car runs its control script on the room server, which draws nothing, so put this script on a separate object whose Script runs on is "presentation", with vehicle pointing at the car. Each browser then draws its own marks; nothing about a trail is replicated.

Tyre smoke

For smoke as well as marks, parent a particle emitter to the car at a rear wheel, with simulation space world so the smoke stays where it was laid while the car drives on, and attach lua/tyre_smoke.lua to the emitter. It reads the car through getParent() and raises the emission rate with how fast the car slides sideways, plus a puff under hard braking. See Particles for settings that look like smoke.

Tracked vehicles

setTrackDriverInput(forward,leftRatio,rightRatio,brake) uses independent track ratios for skid steering. setLeftRatio and setRightRatio update them independently. A ratio is how fast that track turns relative to the engine: equal ratios drive straight, unequal ones turn, and opposite signs pivot on the spot. Both ratios at zero hold the tank still with its brakes on, which is what a tank is built with and what the stock tank script sends when nobody is driving. The track differential ratio is an authoring-time field for the same reason as the wheeled tuning fields above.

setForwardInput, setBrakeInput, getVehicleForwardSpeed(), getVehicleRPM(), getVehicleGear(), isWheelInContact(index), and getWheelContactNormal(index) work on a tracked vehicle as well. setDriverInput, setRightInput, and setHandBrakeInput do nothing on one: a tank steers with its ratios, not a steering angle.

Vehicles played by a bot

A wheeled or tracked vehicle has the same Played by setting as a character: Player (the default), or Bot: Wander, Roam, Script or Idle. A bot feeds the vehicle's own driving script the input a player would, so the stock driving scripts drive an AI car with no changes: moveAxisY is the throttle and moveAxisX the steering, plus input.aimYaw, the heading the bot wants, which the point-and-go script above already steers toward. Through MCP it is the object's botBrain field; vehicles_create_wheeled and vehicles_create_tracked take it as bot_brain, so an AI car or tank is created in one call. From Lua, setBotBrain and getBotBrain. A Wander or Roam bot's settings work on a vehicle too. Speed is how far the bot pushes the stick, so for the stock driving scripts it is the throttle: a lower Speed drives a calmer AI car. The stock scripts brake on fire, and the wheeled one pulls the handbrake on jump, so a Wander bot taps both now and then. Turn Fires and Jumps off and it drives without them. See Played by a bot for the brains, their settings and onBotThink.

How a vehicle looks

Every new vehicle arrives with a model already on it: a pickup for the wheeled presets, a sport bike for the motorcycle controller, and a tank for the tracked presets. Nothing has to be chosen to get something that looks like a vehicle.

Chassis Mesh replaces that model with any GLB, GLTF, FBX, or OBJ asset in the project — on tracked vehicles as well as wheeled ones. Chassis Mesh Fit below it places the model inside the vehicle, and Fit & Center sizes it to the chassis box in one click. That fit moves only the visual: the object's own Scale fields are what resize the physical chassis, its wheels, and its suspension. An FBX chassis is converted from centimetres to metres before the fit's scale multiplies it, as for a GLB; before 16 October 2026 the editor drew an FBX chassis a hundred times too large.

Wheels and track belts are never part of the chassis model. They are drawn from the vehicle's Jolt wheel layout, which is what lets them steer, spin, and ride their suspension independently of the hull. A model that ships its own road wheels has them removed as it loads, matched by name (wheel-front-left, Tire_03, and similar), so they are not drawn twice with one copy frozen to the body.

A tracked vehicle's belts carry a tread that moves with the track. Each side scrolls at its own track's speed, so the top and bottom runs travel in opposite directions and a tank turning on the spot shows one belt running forward and the other back. The inspector's Show track belt switch turns the belts off.

Colouring the running gear

A vehicle's Material tints its body. The running gear has its own fields, because rubber and steel should not follow the paint: Tire Color, Rim Color, and — on a tracked vehicle — Track Color. All three are also settable through scene_objects_update, as 0-1 RGB. Like material colours, they are linear RGB rather than the sRGB of a hex code, so convert a palette colour first; the colour picker's hex is sRGB and is converted for you. See Assets, materials, and shaders.

They take effect immediately, without rebuilding the vehicle constraint, so dragging a colour picker stays smooth. Leave one unset and it keeps its default: near-black tires, light steel rims, and a dark steel track.

Why a new car is red without you choosing anything

The default material means "keep the model's own materials" on anything loaded from a file, so a bundled or imported body arrives in the colours it was authored in and only a material you pick yourself overrides them. The running gear never followed that rule, which is why it needs colour fields of its own instead of inheriting the body's.

Constraint presets

Add An Object → Constraint Presets builds a ready-made joint between two selected physics bodies: Door Hinge, Sliding Platform, Rope, Motorized Spinner or Weld. Each uses an existing constraint type with starting settings you can change in Properties. With an eligible pair selected, the constraint choices appear before the ordinary object catalogue. The plain Constraint entry remains available for choosing bodies afterwards.

Select the two bodies first. Select both bodies together, then open the menu. A plain click replaces the selection, so Shift-drag a box around both in the viewport, or press Cmd+A (Ctrl+A on Windows and Linux) when they are the only objects in the scene. The order you select them in makes no difference. Each must have a rigid physics body of its own: a cube, sphere, cylinder, capsule, mesh, water, height field, or wheeled or tracked vehicle that is not a soft body or visual-only, and is not a child whose collider is merged into its parent's. At least one of the two must be dynamic and not a trigger. Body A is the frame or anchor and Body B the door or platform, and a dynamic body is always chosen as Body B: make the frame or anchor static and the door or platform dynamic, and the roles follow. If both are dynamic, the one earlier in the scene's object order becomes Body A, and the menu says so. Either way, the preset's line in the menu names the object it will use for each role before you choose it, and the inspector's Body A and Body B pickers can swap them afterwards. With any other selection the presets are disabled, the menu says why and how to select both bodies together, and nothing is created.

PresetWhat it creates
Door HingeA hinge constraint named "Door Hinge". Min Limit -90° and Max Limit 90°. The hinge axis is the constraint's local +Y, upright while the constraint is unrotated. It is placed halfway between the two bodies' positions.
Sliding PlatformA slider constraint named "Sliding Platform". Min Limit -2 and Max Limit 2 metres. The slide axis is the constraint's local +X, horizontal while the constraint is unrotated, so gravity does not drive it. It is placed at the platform's position.
RopeA distance constraint with minimum 0 and maximum equal to the selected bodies' world-space separation when created. It allows slack and limits separation; it is not an elastic spring or a rendered rope. The marker is at Body B, but the attachment is centre to centre.
Motorized SpinnerAn unlimited hinge at Body B's centre, rotating around local +Y. Its velocity motor starts enabled at 45 degrees per second. Turn off Motor Enabled to stop driving it.
WeldA fixed constraint that keeps the bodies' current relative position and rotation. Moving the constraint marker does not change the weld.

The new constraint is selected for you. Choosing a preset selects the constraint it creates, on its own, and opens Properties, so its limits, position and motor are ready to adjust. Properties takes the place of the Objects panel the menu is in, or opens in an empty side panel; it does not close an open AI chat or library. Undo removes the constraint and clears it from the selection; redo puts it back without selecting it. The plain Constraint entry leaves your selection as it was.

Door Hinge and Sliding Platform use symmetric limits because these are measured from the bodies' pose when the constraint builds, and which way counts as positive depends on the scene. Narrow one side, for example, to stop a door swinging into its wall, and check the direction with a simulation run. Rotate the constraint to turn its axis. Motors start off except for Motorized Spinner; configure them in Properties or from a script (see Constraint motors). Motor strength keeps the existing Jolt defaults and Lua controls.

Move the hinge to the door's edge

A hinge turns about the constraint's position. The Door Hinge preset puts that halfway between the frame's and the door's positions, which is the door's edge only when the two objects meet there. For a door whose position is its centre, the door would swing about the wrong line. The new constraint is already selected, so before you press Play, move it to the edge the door should turn on.

Any constraint from selected bodies

Add An Object → Constraints from Selected Bodies offers all ten types: Fixed, Point, Hinge, Distance, Swing-Twist, Slider, Six-DOF, Cone, Pulley and Path. Select the same eligible pair first; the menu names Body A and Body B. Choosing a type binds those bodies, selects the new constraint and opens Properties under the same rules as a preset. Set its limits, axes, motor or path there before Play. Pulley starts with a fixed point 2 metres above each body so neither rope segment has zero length. Path starts with a horizontal 4-metre segment centred on Body B. Other types use their normal unset limits and motor off.

Units and validation

Linear distances, offsets, pulley points and slider position targets are labelled in metres (m), and linear motor speed in m/s. Angular limits and hinge position targets use degrees (deg); hinge speed uses deg/s. Six-DOF rotation limits are entered in degrees too.

For every type, Properties warns when a body is missing, removed, has no rigid body of its own, is used on both ends, or neither body is dynamic. It also warns about reversed hinge, distance, twist, slider, six-DOF and pulley ranges. Blank distance maximum uses the authored separation for this check; blank twist and limited six-DOF bounds use zero. Path fields explain missing points, and warn about removed mesh sources or overlapping points that cannot form a curve. These warnings do not rewrite the stored settings.

Seeing a hinge's or slider's axis

While a hinge or slider constraint is selected, whether it came from a preset or was set up by hand, the viewport draws its axis, so you can check which way a door will turn or a platform will slide without pressing Play or reading the rotation numbers.

  • Hinge: a yellow line through the pivot along the constraint's local +Y, a ring around it (the door turns about this line), and an arrowhead on the positive end.
  • Slider: a yellow line along the constraint's local +X with an arrowhead on the positive end. When both Min Limit and Max Limit are set, a green line marks the travel from Min to Max along the axis, with a tick across it at each end. If either limit is blank, that side is unlimited and no range is drawn. If Min is above Max, the inspector warns that no travel range is drawn.

The axis follows the constraint as you move or rotate it, including any rotation from a parent group. Hinge limit angles are not drawn, and the range shows where the limits sit relative to the pivot when the run starts; which way counts as positive can still come out reversed, as described above, so check a one-sided limit with a run. The guide is shown in the editor only: it disappears when you deselect the constraint, and it is left out of Play and screenshots.

Path constraints

A Path constraint makes one body ride along a curve: a gondola on a cable, a roller-coaster car, a platform on a winding route, a train on a loop. Add a Constraint object and set its Type to Path. Body A carries the curve and Body B rides it. Body B must be dynamic. Use something static for Body A, such as the ground or a rail: the curve is fixed to Body A when the constraint builds and moves with it from then on.

The Path field chooses where the curve comes from:

  • This object's control points. A smooth curve through every point: at least two, or three for a closed loop, and at most 256. The points are relative to the constraint object, so moving or rotating it moves the whole curve. Add points with Add point, type coordinates into the numbered list, or click a point in the viewport and drag it with the move gizmo. Delete removes the point you are holding; Esc, or clicking the point again, lets go of it.
  • Track. Pick a generated track mesh and Body B follows the centre of its road, wherever the track is placed. It loops if the track does.

Closed loop joins the last point back to the first, so Body B can circle forever. Import SVG turns a drawing into control points: upload an SVG file or paste one, or paste bare path data, choose whether it lies on the ground plane or stands upright, and give the length of its longest side in metres. The longest path in the drawing is used, simplified to at most 128 points, and it replaces any points already there.

Attach at is where Body B joins the curve, in metres from the first point. Leave it blank and Body B attaches at the nearest point on the curve and keeps its current offset from it, so the simplest setup is to place Body B on the curve. Rotation sets how Body B may turn: Free lets it spin, as a hanging load should; Turn with the path steers it round the bends like a train car; Fully constrained also stops it rolling; and the three Around … only options allow rotation about one axis of the curve. Friction resists motion along the curve, in newtons, while no motor is driving it.

Through MCP, a path constraint is an ordinary constraint object with constraintType: "path" and the fields pathPoints, pathClosed, pathSourceId (the id of a mesh made by assets_generate_track, which takes the place of the points), pathFraction, pathRotationConstraint, and pathMaxFrictionForce.

Constraint motors

Hinge, slider, and path constraints expose setConstraintMotorState("off"|"velocity"|"position"), setConstraintTargetVelocity(value), setConstraintTargetPosition(value), and getConstraintCurrentValue().

On a hinge the values are degrees: target velocity in degrees per second, and target position and current value as an angle in degrees. On a slider they are metres and metres per second. On a path they are metres along the curve: target velocity in metres per second, and target position and current value as the distance from the first point. A target only drives the joint while the motor is in the matching state, so call setConstraintMotorState("velocity") or ("position") first. The constraint's own Motor settings do the same from the moment the scene plays, with no script. On a swing-twist or six-DOF joint these scalar targets do nothing and getConstraintCurrentValue() returns nil; use the rotation targets below. On any other object the setters do nothing.

Motor strength

setConstraintMotorSettings(settings, part) sets how strong a motor is, on hinge, slider, path, swing-twist, and six-DOF joints. settings is a table with any of frequency (Hz, default 2), damping (1 is critically damped, the default), maxForce (newtons; the cap for slider and path motors), and maxTorque (newton-metres; the cap for hinge, swing-twist, and six-DOF motors). Only the fields you give change. Both caps start effectively unlimited. Frequency and damping only matter in position mode: a higher frequency pulls toward the target more stiffly, and 0 is a rigid drive limited only by the cap. The caps apply in both modes, so a low maxTorque is how a limb goes limp or a motorised door gives way when pushed. A negative or non-finite value, or a misspelt key, is reported and the call does nothing. getConstraintMotorSettings(part) returns {frequency=, damping=, maxForce=, maxTorque=}, or nil on an object without a motor.

Swing-twist motors and active ragdolls

A swing-twist joint has two motors, swing and twist. setConstraintMotorState(mode, part) and the settings calls take an optional part, "swing" or "twist"; leave it out for both (getConstraintMotorSettings reads swing by default). A six-DOF joint's rotation motors work the same way, with twist about its X axis and swing about Y and Z; its translation motors are not reachable from Lua.

In position mode, setConstraintTargetOrientation(x, y, z, w) sets the rotation to hold. In velocity mode, setConstraintTargetAngularVelocity(x, y, z) sets a spin in degrees per second. Both are in the joint's own frame, measured from the pose the two bodies were in when the joint was built: the identity quaternion (0, 0, 0, 1) holds that rest pose, X is the twist axis (the constraint object's local +X), and Y and Z are the swing axes. The orientation is body B relative to body A. A target beyond the joint's swing and twist limits is clamped to them, and those limits default to 0, which locks the joint, so set them first. getConstraintRotation() returns the joint's current rotation in the same frame, so a script can compare where a joint is with where it is driving it.

-- A hip that holds 45 degrees of twist, firmly but not unbreakably.
function init()
    gameObject.setConstraintMotorState("position")
    gameObject.setConstraintMotorSettings({ frequency = 8, damping = 1, maxTorque = 300 })
    local half = math.rad(45) / 2
    gameObject.setConstraintTargetOrientation(math.sin(half), 0, 0, math.cos(half))
end

Changing a running motor's settings or target wakes its bodies. Stop puts back every joint a script changed: its authored motor and the default strength. In a multiplayer room, drive motors from the authority script that owns the joint.

Ragdolls

A ragdoll takes a skinned model and simulates its skeleton: one capsule body per bone, joined by Swing-Twist constraints. It is its own object type rather than a switch on a mesh, because what is simulated is the rig rather than the shape.

Point Mesh File at a skinned GLB, GLTF, or FBX asset and the bones are detected from the skeleton automatically. Nothing else is required to get a body that falls over.

The three modes

ModeBehaviour
kinematicThe bodies follow the playing animation and are unaffected by physics. The ragdoll pushes other things and is pushed by nothing — an animated character with a real collider.
dynamicThe bodies fall freely under gravity and collision, and animation input is ignored entirely. This is the classic limp ragdoll.
poweredThe bodies are dynamic, but constraint motors drive them continuously toward the playing animation's pose. The character holds its animation, can be knocked off it by an impact, and fights its way back.

Tracked Animation, with its own speed and loop settings, is the pose source for kinematic and powered. It is ignored in dynamic mode, which has no pose to track.

Joint limits, and what you get without setting any

Each bone joint has four limits in degrees: Normal Half-Cone and Plane Half-Cone bound the swing, and Min Twist and Max Twist bound the rotation along the bone. A joint with a zero normal cone and a wide plane cone behaves like a hinge, which is what an elbow or a knee should do.

A limit is resolved in three steps, and the first one that has a value wins:

  1. A per-bone override, if you set one for that bone. Overrides are keyed by bone name, so they survive re-detecting the skeleton or swapping in a differently ordered rig.
  2. The ragdoll's own default, which applies to every joint at once.
  3. An anatomical preset matched against the bone's name.

That last step is why a standard humanoid rig behaves sensibly before anyone opens the joint fields. Bones whose names contain spine, chest, neck, head, shoulder, clavicle, arm, forearm, hand, wrist, thigh, hip, leg, knee, shin, foot, ankle, toe, or a finger name are each given limits appropriate to that joint — a forearm and a shin get hinge-like limits, a head and a hip get wide cones, a spine gets very little.

Setting a ragdoll-wide default therefore replaces the presets rather than adjusting them: every joint gets the same limits, including the elbows. Prefer per-bone overrides when only one joint is wrong.

Bone Radius Scale sets each capsule's radius as a fraction of its bone's length, so one number thickens or thins the whole body proportionally.

Limbs that jitter against each other

Adjacent bodies overlap at every joint, and a dynamic ragdoll will buzz as they push apart. Put the ragdoll's parts in a shared collision group and disable the neighbouring pairs — see Collision groups.

Controlling a ragdoll from Lua

A ragdoll's script can switch its mode, push individual bones and tune its motors while the game runs. Bone names come from gameObject.getRagdollBones(), which lists every bone that has a physics body (it is empty until the model has loaded).

  • setRagdollMode("animated") follows the animation exactly, "powered" lets joint motors pull the body toward the animation so hits knock it off pose, and "limp" is a free ragdoll for a stun or a fall. getRagdollMode() returns the current one. Stop restores the mode you set in the inspector.
  • Going limp keeps the body's momentum. Going back to "animated" snaps to the animation in one step, so recover through "powered" first. A ragdoll set to Dynamic in the inspector has no animation, so animated and powered just hold its pose.
  • setRagdollMotorStrength(strength, bone) sets how hard a powered ragdoll holds its pose: 1 is the default, 0.3 is loose, 5 is stiff (up to 10), and 0 lets a joint go slack. Leave out bone for every joint. A table {frequency=, damping=, maxTorque=} sets the spring directly.
-- Hit reaction, then a stun
gameObject.setRagdollMode("powered")
local chest = gameObject.getRagdollBonePosition("mixamorig:Spine2")
gameObject.addRagdollBoneImpulse("mixamorig:Spine2", 30, 5, 0, chest)
-- later:
gameObject.setRagdollMode("limp")

Ragdolls are not replicated in multiplayer rooms, so use ragdoll control in single-player games.

Navigation agents

Pathfinding moves an object across a navigation mesh baked from the scene's static, solid geometry: cubes, spheres, cylinders, capsules, meshes, and height fields that are static, are not sensors, and (for meshes) have a collider. Dynamic props, water, triggers, and meshes with collisionType "none" are left out.

  • The mesh is baked the first time a run asks for it, by registerForPathfinding or any navigation query, so scenes without agents never pay for it. It is discarded at Stop, so the next Play reflects your edits. Pressing Play again on a scene whose geometry and navigation settings have not changed reuses the last bake.
  • Baking large scenes. In the editor and the published player the mesh bakes in a background worker, so the game keeps running while it does; a city of a few thousand objects takes a few seconds. Until it is ready, moveTo waits and the queries return nil, so nil-check them every frame rather than once. In a multiplayer room the room server bakes it.
  • To see what agents will walk on before you press Play, use Bake and Show mesh in the Navigation section of Scene Settings. The line beneath them reports how many objects went into the bake, or that it found no walkable geometry. That bake is a preview; a run still bakes its own.
  • Agent size comes from the scene's Navigation settings (Scene Settings panel, or the navigation argument of scenes_update): radius 0.4 m, height 1.8 m, step 0.4 m, and slope 45 degrees by default.
  • Cell size and narrow walkways. Leave cell_size (set only through scenes_update) unset unless you need to change it: the default is half the agent radius, 0.2 m for the default agent. Raising it no longer makes the bake meaningfully faster, and it closes narrow walkways, because the bake keeps the agent radius, rounded up to whole cells, clear of every edge. The table after this list gives the narrowest walkway with drops on both sides, such as a raised sidewalk or a bridge, that still connects for the default agent. Walls either side are more forgiving, but an obstacle standing on a walkway, such as a bin or a lamp post, narrows it by more than its own width at a coarse cell. If paths along a sidewalk come back nil or detour round the block, check the cell size first. The browser console warns when the cell is larger than the agent radius.
  • An agent must be a character or a dynamic body. Agents are moved by velocity, which a static object ignores.
  • Steering is horizontal: an agent keeps its own falling speed and turns to face its path.
  • In a multiplayer room only authority scripts may call registerForPathfinding, moveTo, followPath, followWaypointPath and stopMovement. The queries work in any script.

The narrowest walkway with drops on both sides that still connects, for the default 0.4 m agent:

Cell sizeNarrowest walkway
0.1 m1.25 m
0.2 m (the default)1.5 m
0.3 m2 m
0.4 m2.75 m
0.5 m3.25 m
0.75 m5 m
MethodBehavior
registerForPathfinding(speed)Makes this object an agent moving at speed metres per second and starts the bake. Calling it again only changes the speed, so one agent can walk a patrol and run a chase.
moveTo(x,y,z)Plans a path to the point and follows it. Until the mesh has baked the agent waits (isMoving() is already true); an unreachable point stops it. A new moveTo replaces whatever it was doing.
followPath(waypoints)Walks straight lines through a list of {x, y, z} points without consulting the navigation mesh.
stopMovement()Ends the current route and brings the agent to rest where it stands. Gravity still applies, and the next moveTo or followPath starts it again. Calling it on an agent that is already idle does nothing, so a script can keep driving its own velocity afterwards.
isMoving()True while following a route, awaiting its bake, or waiting at a patrol stop. False when the command finishes, after stopMovement(), and when a target could not be reached.
getPathToTarget(x,y,z)A path from this object to the point, or nil.
getRandomNavPoint(radius)A random reachable point within about radius metres, for wandering, or nil.

Queries wait for the bake

getPathToTarget and getRandomNavPoint return nil until the mesh has baked, which takes a few seconds in a large scene, so nil-check them and try again next frame; never treat the first nil as "unreachable". When chasing, call moveTo again once the target has moved a metre or two rather than every frame.

Scene scripts, and object scripts through scene, can query between arbitrary points with scene.findPath(from, to) and scene.getNearestNavPoint(point), both taking {x=, y=, z=} tables.

local PATROL_SPEED = 2.2
local player

function init()
    player = gameObject.getObjectByName("Player")
    gameObject.registerForPathfinding(PATROL_SPEED)
end

function update(deltaTime)
    local here = gameObject.getPosition()
    local target = player.getPosition()
    local dx, dz = target.x - here.x, target.z - here.z
    if dx * dx + dz * dz < 4 then
        -- Close enough: stand still. Only the first call does anything.
        gameObject.stopMovement()
    elseif not gameObject.isMoving() then
        local spot = gameObject.getRandomNavPoint(8)
        if spot then gameObject.moveTo(spot.x, spot.y, spot.z) end
    end
end

Authored waypoint patrols

Add Navigation → Waypoint Path from Add An Object. Edit the numbered stops in its inspector: position, label, wait in seconds, and arrival event. Add, duplicate, remove, or reorder stops there. Choose Move point, or click a viewport handle, to drag a stop with the transform gizmo. A drag is one undo entry; Esc releases the handle and Delete removes the selected point. Points are local to the path and follow its parent transforms. A path needs at least two stops to run; an incomplete path remains editable. Paths have no physics body and are invisible through gameplay cameras.

Select a character or a dynamic solid rigid body and choose its Navigation patrol path, speed in metres per second, and traversal. It starts at the nearest stop. Once ends at the last stop; Loop connects the last stop to the first; Ping-pong reverses at each end. Static bodies, sensors, soft bodies, visual-only objects, and triangle-mesh colliders cannot patrol. No player-input control script or bot brain is needed. In a room, automatic patrols run only on the authority: set multiplayer.scriptRole: "authority", and set replicate: true on scriptless bodies. Player-controlled objects do not automatically patrol.

Each leg is routed over the navigation mesh. Off-mesh stops and unreachable legs end the patrol instead of treating a partial corridor as arrival. scene.findPath and getPathToTarget also return nil for partial corridors. In the editor view, the selected running agent has a yellow line showing its remaining computed corners; authored path outlines are cyan. Rebuild the mesh after geometry changes. Surface-click insertion, surface/navmesh drag snapping, and a stale-bake indicator are not yet available.

From Lua, scene.getWaypointPath(idOrName) returns the path ID, name, and world-space points with their metadata, or nil. gameObject.followWaypointPath(idOrName, traversal?) starts the route; traversal is "once", "loop" (default), or "pingPong". A missing or incomplete route returns false. Call registerForPathfinding(speed) to choose the speed; calling it again changes speed without cancelling the route.

Waits use game time, and isMoving() stays true during a patrol wait. A stop with an event name calls onWaypointReached(eventName, pathId, pointIndex) on the moving object's own script, on arrival before its wait. Point indices are 1-based. Arrival is committed before the callback, so the handler may safely change movement. Explicit Lua moveTo, followPath, followWaypointPath, or stopMovement cancels an inspector-started patrol for the rest of that run. Resume explicitly with followWaypointPath, or start a fresh Play. Call stopMovement before driving velocity yourself. followPath(points) continues to follow direct straight segments without navmesh routing.

function init()
    gameObject.registerForPathfinding(1.1)
    gameObject.followWaypointPath("Guard patrol", "loop")
    gameObject.enableAutoAnimation({})
end

function update(dt)
    gameObject.updateAutoAnimation()
end

function onWaypointReached(eventName, pathId, pointIndex)
    print("Reached " .. pointIndex .. ": " .. eventName)
end

Follow a generated track

A navigation mesh is the wrong tool for a race car. On a generated track mesh, getTrackPath() returns the centreline the road was swept along: {closed = true, points = {{x=, y=, z=, width=}, ...}} in world space, one point about every 5 m. It returns nil for other objects and for tracks generated before the path was recorded; regenerate those with their existing recipe and asset id. Call it once in init.

To drive an AI car along it, find the nearest point, steer toward the point a lookahead distance further along, and lower the target speed where the path bends. Don't copy a track recipe's control points into a script: they are in the model's coordinates and go stale when the track moves.

For something that should stay on the road without being steered at all, such as a ride car or a pace car, use a path constraint with the track as its source instead.

To put a car that has left the road back on it, use gameObject.resetPhysicsState(x, y, z, qx, qy, qz, qw) rather than setPosition. It moves the vehicle, clears its velocity, spin, and driver input, stops its wheels and tracks, idles the engine in neutral, and wakes it, all in one call; setPosition keeps the momentum the car had when it left. The rotation is optional.