Falling boxes with Box2D
Updated
Box2D, the 2D physics engine compiled to JavaScript, imported from a CDN, drops six boxes on a ground seen through an Orthographic Camera, and a click kicks a box up: the script steps the Box2D world every frame and copies each body’s position and angle to its box.
Watch the boxes fall and stack. Click a box to kick it up, or click the scene and press Space to drop them all again.
Falling boxes with Box2D
#pragma import(Box2D="https://cdn.jsdelivr.net/npm/box2d.js@1.0.4/build/Box2D_v2.3.1_min.js")#pragma lifecycle(startup, update, dispose)
const SIDE = 0.6; // box side, in metres: Box2D's units are metres tooconst STEP = 1 / 60; // Box2D wants a fixed time step, in secondsconst AWAKE = '#f59e0b';const ASLEEP = '#60a5fa'; // a body at rest that Box2D stopped simulatingconst KICK = 4; // m/s upwards a click gives a box: a gentle hop
let world = null;let point = null; // two b2Vec2s, reused to hand vectors to Box2Dlet at = null;let boxes = [];let pending = 0; // seconds of simulation not run yet
function addBody(entity, type, width, height) { const def = new Box2D.b2BodyDef(); def.set_type(type); point.Set(entity.position.x, entity.position.y); def.set_position(point); def.set_angle(entity.rotation.z); const body = world.CreateBody(def);
const shape = new Box2D.b2PolygonShape(); shape.SetAsBox(width / 2, height / 2); // half sizes body.CreateFixture(shape, 1).SetFriction(0.6); // density 1 kg/m² Box2D.destroy(shape); // Box2D keeps copies: free ours Box2D.destroy(def); return body;}
function startup() { point = new Box2D.b2Vec2(0, -9.81); at = new Box2D.b2Vec2(0, 0); world = new Box2D.b2World(point); // gravity, m/s² world.SetAllowSleeping(true); // bodies at rest sleep until something hits them
const ground = findEntity('Ground'); addBody(ground, Box2D.b2_staticBody, 8, 0.4);
boxes = self.parent.children .filter((child) => isEntity(child) && child !== self && child !== ground) .map((entity) => ({ entity, start: [entity.position.x, entity.position.y], body: addBody(entity, Box2D.b2_dynamicBody, SIDE, SIDE), material: entity.getComponent(StandardMaterialComponent), awake: true, }));}
function dropAgain() { boxes.forEach(({ body, start }) => { point.Set(start[0], start[1]); body.SetTransform(point, Random.range(-0.5, 0.5)); point.Set(0, 0); body.SetLinearVelocity(point); body.SetAngularVelocity(0); body.SetAwake(true); });}
// The box under the pointer gets an upward impulse at the point clicked, so it hops and turns a little.function kick() { const hit = GraphicsRaycaster.fromScreen(Input.mouse.position()).hit(boxes.map((box) => box.entity)); const box = hit && boxes.find((b) => b.entity === hit.entity); if (!box) return; point.Set(0, box.body.GetMass() * KICK); // impulse = mass × change in speed at.Set(hit.point.x, hit.point.y); box.body.ApplyLinearImpulse(point, at, true); // true wakes a sleeping box}
function update(dt) { if (Input.keyboard.isKeyReleased(Key.Space)) dropAgain(); if (Input.mouse.isButtonReleased(MouseButton.Left)) kick();
pending += dt; while (pending >= STEP) { world.Step(STEP, 8, 3); // velocity and position iterations pending -= STEP; } boxes.forEach((box) => { const position = box.body.GetPosition(); box.entity.setPosition(position.get_x(), position.get_y(), 0); box.entity.setRotation(0, 0, box.body.GetAngle());
const awake = box.body.IsAwake(); if (awake !== box.awake) { box.awake = awake; // recolour only when the state changes box.material.setProps({ color: awake ? AWAKE : ASLEEP }); } });}
function dispose() { Box2D.destroy(world); // frees every body with it Box2D.destroy(point); Box2D.destroy(at);}How it works
Section titled “How it works”The script is explained step by step in Falling boxes with Box2D.
Open it in XR Creator
Section titled “Open it in XR Creator”Download the project file below, then import it in XR Hub with Projects › New › Import, as described in Projects and templates. It opens in XR Creator with the same scene you see running above, each script already attached to its Behavior entity. From there you can edit the scripts, adjust components and their props, preview your changes, and deploy the result as a world of your own.
Box2dStack.xrproj