Forces and impulses
Updated
A dynamic body moves because something acts on it: gravity, a collision, or your script. This page covers the ways a script acts on a body through PhysicsRigidBodyComponent: instant impulses for kicks and jumps, continuous forces for thrusters and wind, torques for spin, direct velocities for precise control, per-body gravity, and the sleep state that lets resting bodies cost nothing.
Before you start
Section titled “Before you start”- The body you push must be a dynamic Rigid Body. Kinematic and fixed bodies ignore forces; move kinematic bodies with kinematic moves instead. See Rigid bodies and colliders.
- Get the component once, in
startup:const body = self.parent.getComponent(PhysicsRigidBodyComponent)(the Behavior sits under the body). - Vectors are plain
{ x, y, z }objects in world space; aTHREE.Vector3works too. - All of this acts only in play, while the body is simulated (
body.isSimulated).
Impulse, force or velocity?
Section titled “Impulse, force or velocity?”These three tools answer different needs:
- Impulse. An instant change of momentum, applied once. Use it for events that happen in a moment: a kick, a jump, an explosion, a hit. The heavier the body, the less a given impulse changes its speed.
- Force. A push that keeps acting on every physics step until you remove it. Use it for things that last: a rocket’s thrust, wind, a magnet. A force gradually speeds the body up.
- Velocity. Overwriting the speed directly. Use it when you need an exact result, such as a jump pad that always launches at the same speed, or a speed limit. It ignores the body’s mass.
Each has a turning counterpart: applyTorqueImpulse for an instant spin, addTorque for a lasting twist, setAngularVelocity for an exact spin rate.
Members
Section titled “Members”| Member | Description |
|---|---|
apply |
Instant change in momentum at the centre of mass. The body moves without starting to spin. |
apply |
The same at a world point. Hitting off-centre also adds spin, like a kick at the edge of a ball. |
apply |
Instant change in angular momentum: a sudden spin about the given axis. |
add |
A force applied on every step until resetForces(). Each call adds to the forces already acting. |
add |
A torque applied on every step until reset. |
resetForces() |
Remove every force added with addForce. |
reset |
Remove every torque added with addTorque. |
set |
Overwrite the velocity, in metres per second. |
set |
Overwrite the spin, in radians per second about each world axis. |
linear |
The current velocity, { x, y, z }; zero without a live body. |
angular |
The current spin, { x, y, z }; zero without a live body. |
set |
Override the authored gravityScale of this body during play, from 0 (floats) to 1 (normal gravity). The override survives physics rebuilds; editing the gravityScale prop replaces it. |
wakeUp() |
Wake a sleeping body so it reacts at once. |
Sleeping and waking
Section titled “Sleeping and waking”When a dynamic body comes to rest, the simulation puts it to sleep: it stops computing it until something touches it or a script acts on it. Sleeping bodies cost nothing, which is why a pile of a hundred crates is cheap once it settles.
- The
sleepprop (defaulttrue) allows sleeping. Turn it off only for bodies that must never pause. - Contacts with moving bodies wake a sleeper. When your script changes something a sleeping body should react to, such as its gravity, call
wakeUp()so it reacts at once.
With an enabled Signal Emitter on the entity, a movable body sends two events:
| eventType | Constant | data | When |
|---|---|---|---|
Physics |
Event |
{} |
The body came to rest and was put to sleep. |
Physics |
Event |
{} |
It moves again. |
These events are wired when the body is built, so the Signal Emitter, with a signal set, must be on the entity at that time. A body with sleep: false never sends them.
Examples
Section titled “Examples”1. A jump pad
Section titled “1. A jump pad”A pad launches anything that lands on it straight up, always at the same speed.
#pragma lifecycle(startup)
const LAUNCH_SPEED = 9; // metres per second, upwards
function startup() { on('pad', (event) => { if (event.eventType !== EventType.PhysicsCollider.IntersectionEnter) return; const other = findEntity(event.data.otherEntityId || ''); const body = other?.getComponent(PhysicsRigidBodyComponent); if (!body || body.bodyType !== 'dynamic') return;
const v = body.linearVelocity(); body.setLinearVelocity({ x: v.x, y: LAUNCH_SPEED, z: v.z }); });}A sensor pad that sets the vertical velocity of every dynamic body entering it, so light and heavy bodies leave at the same speed.
Watch the bodies bounce on the pad. Drag one off the pad or back onto it.
- The pad’s collider is a sensor, so bodies pass into it instead of bouncing off, and it reports
intersection-enter. otherEntityIdnames the body that entered;findEntityfinds it, andgetComponentits Rigid Body, if it has one.- The
bodyTypecheck skips fixed and kinematic bodies, which velocities do not move. setLinearVelocitykeeps the horizontal speed and replaces the vertical one. Every body leaves at the same speed, light or heavy. WithapplyImpulsea heavy crate would barely lift.
2. A thruster you hold
Section titled “2. A thruster you hold”While the player holds Space, a hover drone pushes upwards; on release, the push stops.
#pragma lifecycle(startup, update)
const THRUST = { x: 0, y: 30, z: 0 }; // a steady upward push
let body;let firing = false;
// On a dynamic drone with a Rigid Body and a collider.function startup() { body = self.parent.getComponent(PhysicsRigidBodyComponent);}
function update() { const held = Input.keyboard.isKeyPressed(Key.Space); if (held === firing) return;
firing = held; if (firing) { body.addForce(THRUST); } else { body.resetForces(); }}While Space is held, a lasting upward force lifts a drone; releasing Space removes it with resetForces, and gravity brings the drone back down.
Click the scene, then hold Space to lift the drone and let go to drop it. Drag to orbit the camera, scroll to zoom.
- A force lasts until it is removed, so the script adds it once, when Space goes down, not every frame.
firingremembers whether the thrust is on; the earlyreturnskips frames where nothing changed.resetForcesremoves the thrust when Space is released, and gravity pulls the drone back down.- Tune
THRUSTagainst the drone’smass: the push must be larger than its weight for it to rise.
3. Kick a ball where it was clicked
Section titled “3. Kick a ball where it was clicked”A click on the ball kicks it away from the camera, at the point that was hit, so an off-centre click also makes it spin.
#pragma lifecycle(startup, update)
const STRENGTH = 4;const push = new THREE.Vector3();
let ball;let body;
function startup() { ball = findEntity('Ball'); body = ball.getComponent(PhysicsRigidBodyComponent);}
function update() { if (!Input.mouse.isButtonReleased(MouseButton.Left)) return; const ray = PhysicsRaycaster.fromScreen(Input.mouse.position()); const hit = ray.hit(ball); if (!hit) return;
push.copy(ray.ray.direction).multiplyScalar(STRENGTH); body.applyImpulseAtPoint(push, hit.point);}A click on the ball casts a physics ray and applies an impulse along it at the point hit, so an off-centre click also sets the ball spinning.
Click the ball to kick it away from you; click its edge to make it spin. Drag to orbit the camera, scroll to zoom.
PhysicsRaycaster.fromScreenmakes a ray from the camera through the mouse;hit(ball)tests only the ball’s colliders. See Picking and raycasts.ray.ray.directionis the direction the ray travels, away from the camera.applyImpulseAtPointpushes athit.point. Hit dead centre, the ball rolls straight; hit at its edge, it also spins.pushis one vector reused every click.
4. A low-gravity zone and sleep reporting
Section titled “4. A low-gravity zone and sleep reporting”Bodies inside a zone float gently; outside, they fall normally. A second listener reports when they settle.
#pragma lifecycle(startup)
const FLOATY = 0.15;
// The Zone is a group with a sensor Box Collider and a Signal Emitter with the signal 'zone'.// Each crate has a Rigid Body and a Signal Emitter with the signal 'crate'.function startup() { on('zone', (event) => { const body = findEntity(event.data.otherEntityId || '')?.getComponent(PhysicsRigidBodyComponent); if (!body) return; if (event.eventType === EventType.PhysicsCollider.IntersectionEnter) { body.setGravityScale(FLOATY); body.wakeUp(); } if (event.eventType === EventType.PhysicsCollider.IntersectionExit) { body.setGravityScale(1); } });
on('crate', (event) => { const name = findEntity(event.entityId)?.name; if (event.eventType === EventType.PhysicsRigidBody.Sleep) log(name, 'settled'); if (event.eventType === EventType.PhysicsRigidBody.Wake) log(name, 'moving again'); });}Bodies that enter a sensor zone get a gravity scale of 0.15 and float down gently; leaving it restores normal gravity. A second listener logs when each crate settles or moves again.
Watch the crates over the blue zone drift down while the other one drops. Grab a crate and lift it into the zone again. Drag elsewhere to orbit the camera.
- The zone’s sensor reports when a body enters and leaves it;
setGravityScalechanges only that body’s gravity, during play. wakeUpmakes a body that was asleep inside the zone react at once.- On the way out, the scale goes back to
1, normal gravity. - The crates’ own Signal Emitters send
sleepandwake.event.entityIdis the crate that sent the event.
Snippets
Section titled “Snippets”1. A speed limit
Section titled “1. A speed limit”A dynamic car is pushed by forces elsewhere, but must never exceed a top speed.
#pragma lifecycle(startup, update)
const MAX_SPEED = 12; // metres per second
let body;
function startup() { body = self.parent.getComponent(PhysicsRigidBodyComponent);}
function update() { const v = body.linearVelocity(); const speed = Math.hypot(v.x, v.y, v.z); if (speed <= MAX_SPEED) return;
const scale = MAX_SPEED / speed; body.setLinearVelocity({ x: v.x * scale, y: v.y * scale, z: v.z * scale });}linearVelocity()reads the body’s velocity;Math.hypotgives its length, the speed.- Only when it is too fast does the script scale the velocity down, keeping its direction.
- Overwriting the velocity is the right tool here: a counter-force would have to be recalculated every step.
Common mistakes
Section titled “Common mistakes”- Calling
addForceevery frame. Forces last and add up, so the push keeps growing. Add a force once and remove it withresetForces, or use an impulse each time instead. - Pushing a kinematic or fixed body. Forces, impulses and velocities move only dynamic bodies.
- Expecting the same impulse to move every body the same. An impulse changes momentum: a heavy body moves less. Use
setLinearVelocitywhen every body must reach the same speed. - Local directions.
applyImpulse({ x: 0, y: 0, z: -1 })pushes along world −Z, not “forward” for the body. Convert local directions to world space first. - No
sleeporwakeevents. The Signal Emitter must have a signal when the body is built, and the body’ssleepprop must be on. - Using the editor. Nothing here acts until play starts.