Physics ⚛️
Greetings, Scientist!
Physics class is about using the scientific method and engineering design processes to uncover the mysteries of the natural world!
Please, click and drag to yeet the guy using physics!
ragdollDemo = {
const { Engine, Bodies, Body, Composite, Constraint, Mouse, MouseConstraint, Events } = Matter;
const H = 400; // fixed height in px
let W = 800; // width follows the container (100%)
let dpr = window.devicePixelRatio || 1;
// ---------- DOM ----------
const container = document.createElement("div");
container.style.cssText = `position:relative;width:100%;height:${H}px;border-radius:10px;overflow:hidden;
background:linear-gradient(#f2f6fa,#d3dce6);user-select:none;-webkit-user-select:none;`;
const canvas = document.createElement("canvas");
canvas.style.cssText = `width:100%;height:${H}px;display:block;touch-action:none;cursor:grab;`;
container.append(canvas);
const ctx = canvas.getContext("2d");
const btnStyle = `padding:4px 10px;margin-right:6px;font-size:13px;border:1px solid #8a6a45;
background:#fff8ee;color:#5a4328;border-radius:6px;cursor:pointer;`;
const bar = document.createElement("div");
bar.style.cssText = "position:absolute;top:8px;left:8px;z-index:2;";
const resetBtn = document.createElement("button");
resetBtn.textContent = "Reset";
resetBtn.style.cssText = btnStyle;
const addBtn = document.createElement("button");
addBtn.textContent = "+ Add mannequin";
addBtn.style.cssText = btnStyle;
bar.append(resetBtn, addBtn);
container.append(bar);
// ---------- Physics world ----------
const engine = Engine.create();
const world = engine.world;
engine.gravity.y = 1;
engine.positionIterations = 10;
engine.velocityIterations = 10;
engine.constraintIterations = 4;
let walls = [];
function buildWalls() {
Composite.remove(world, walls);
const t = 200;
const o = { isStatic: true, friction: 0.9, restitution: 0.2, collisionFilter: { category: 1 } };
walls = [
Bodies.rectangle(W / 2, H + t / 2, W + 2 * t, t, o), // floor
Bodies.rectangle(W / 2, -t / 2, W + 2 * t, t, o), // ceiling
Bodies.rectangle(-t / 2, H / 2, t, H * 4, o), // left
Bodies.rectangle(W + t / 2, H / 2, t, H * 4, o) // right
];
Composite.add(world, walls);
}
// ---------- Mannequin ----------
const mannequins = [];
function spawn(x, y, angle = 0, vx = 0, vy = 0, spin = 0) {
const group = Body.nextGroup(true); // parts of one figure never collide with each other
const common = {
collisionFilter: { group, category: 2 },
friction: 0.6, frictionAir: 0.012, restitution: 0.15
};
const box = (dx, dy, w, h, r, density = 0.001) =>
Bodies.rectangle(x + dx, y + dy, w, h, { ...common, density, chamfer: { radius: r } });
const torso = box(0, 0, 40, 64, 12, 0.002);
const head = Bodies.circle(x, y - 44, 16, { ...common, density: 0.0015 });
const uArmL = box(-22, -10, 12, 32, 5), lArmL = box(-22, 21, 10, 30, 4);
const uArmR = box(22, -10, 12, 32, 5), lArmR = box(22, 21, 10, 30, 4);
const uLegL = box(-9, 49, 14, 38, 6), lLegL = box(-9, 87, 12, 38, 5);
const uLegR = box(9, 49, 14, 38, 6), lLegR = box(9, 87, 12, 38, 5);
const joints = [];
const limits = [];
const joint = (a, pa, b, pb, min, max) => {
const c = Constraint.create({
bodyA: a, pointA: pa, bodyB: b, pointB: pb,
length: 0, stiffness: 0.9, damping: 0.1
});
joints.push(c);
limits.push({ parent: a, child: b, min, max });
};
// neck
joint(torso, { x: 0, y: -29 }, head, { x: 0, y: 15 }, -0.9, 0.9);
// shoulders
joint(torso, { x: -22, y: -26 }, uArmL, { x: 0, y: -16 }, -3.0, 3.0);
joint(torso, { x: 22, y: -26 }, uArmR, { x: 0, y: -16 }, -3.0, 3.0);
// elbows (bend one way only)
joint(uArmL, { x: 0, y: 16 }, lArmL, { x: 0, y: -15 }, -2.5, 0.05);
joint(uArmR, { x: 0, y: 16 }, lArmR, { x: 0, y: -15 }, -2.5, 0.05);
// hips
joint(torso, { x: -9, y: 30 }, uLegL, { x: 0, y: -19 }, -1.7, 1.7);
joint(torso, { x: 9, y: 30 }, uLegR, { x: 0, y: -19 }, -1.7, 1.7);
// knees (bend backwards only)
joint(uLegL, { x: 0, y: 19 }, lLegL, { x: 0, y: -19 }, -0.05, 2.5);
joint(uLegR, { x: 0, y: 19 }, lLegR, { x: 0, y: -19 }, -0.05, 2.5);
// drawing order: legs, torso, arms, head
const parts = [
uLegL, lLegL, uLegR, lLegR,
torso,
uArmL, lArmL, uArmR, lArmR,
head
];
const comp = Composite.create();
Composite.add(comp, [...parts, ...joints]);
if (angle) Composite.rotate(comp, angle, { x, y });
for (const b of parts) {
Body.setVelocity(b, { x: vx, y: vy });
Body.setAngularVelocity(b, spin);
}
Composite.add(world, comp);
const m = { comp, parts, joints, limits, torso, head };
mannequins.push(m);
return m;
}
function clearAll() {
for (const m of mannequins) Composite.remove(world, m.comp);
mannequins.length = 0;
}
function dropOne() {
const x = 80 + Math.random() * Math.max(1, W - 160);
spawn(x, 120, (Math.random() - 0.5) * 1.2, (Math.random() - 0.5) * 6, 0, (Math.random() - 0.5) * 0.2);
}
// joint angle limits + speed cap, applied before each physics step
const wrap = a => ((a + Math.PI) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI) - Math.PI;
Events.on(engine, "beforeUpdate", () => {
for (const m of mannequins) {
for (const l of m.limits) {
const rel = wrap(l.child.angle - l.parent.angle);
let ex = 0;
if (rel > l.max) ex = rel - l.max;
else if (rel < l.min) ex = rel - l.min;
if (ex) {
Body.setAngularVelocity(l.child, l.child.angularVelocity - ex * 0.3);
Body.setAngularVelocity(l.parent, l.parent.angularVelocity + ex * 0.15);
}
}
for (const b of m.parts) {
const s = Math.hypot(b.velocity.x, b.velocity.y);
if (s > 45) Body.setVelocity(b, { x: b.velocity.x * 45 / s, y: b.velocity.y * 45 / s });
if (Math.abs(b.angularVelocity) > 0.6) Body.setAngularVelocity(b, Math.sign(b.angularVelocity) * 0.6);
}
}
});
// ---------- Mouse dragging / throwing ----------
const mouse = Mouse.create(canvas);
mouse.pixelRatio = dpr;
// don't hijack page scrolling
for (const ev of ["mousewheel", "DOMMouseScroll", "wheel"]) {
canvas.removeEventListener(ev, mouse.mousewheel);
}
const mouseConstraint = MouseConstraint.create(engine, {
mouse,
collisionFilter: { category: 1, mask: 2, group: 0 }, // only grab mannequin parts, never walls
constraint: { stiffness: 0.2, damping: 0.05, render: { visible: false } }
});
Composite.add(world, mouseConstraint);
// keep tracking / releasing even if the pointer leaves the canvas
const onWinMove = e => mouse.mousemove(e);
const onWinUp = e => mouse.mouseup(e);
window.addEventListener("mousemove", onWinMove);
window.addEventListener("mouseup", onWinUp);
let hint = 1;
// ---------- Rendering ----------
const WOOD = "#e6c8a0", WOOD_TORSO = "#d9b487", WOOD_HOT = "#f6e2c4";
const EDGE = "#8a6a45";
const worldPoint = (body, p) => {
const c = Math.cos(body.angle), s = Math.sin(body.angle);
return { x: body.position.x + p.x * c - p.y * s, y: body.position.y + p.x * s + p.y * c };
};
function drawBody(b, fill) {
const v = b.vertices;
ctx.beginPath();
ctx.moveTo(v[0].x, v[0].y);
for (let i = 1; i < v.length; i++) ctx.lineTo(v[i].x, v[i].y);
ctx.closePath();
ctx.fillStyle = fill;
ctx.fill();
ctx.stroke();
}
function draw() {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
// floor strip
ctx.fillStyle = "rgba(90,70,45,0.18)";
ctx.fillRect(0, H - 6, W, 6);
ctx.lineWidth = 2;
ctx.lineJoin = "round";
ctx.strokeStyle = EDGE;
const grabbed = mouseConstraint.body;
for (const m of mannequins) {
for (const b of m.parts) {
const hot = grabbed === b;
drawBody(b, hot ? WOOD_HOT : (b === m.torso ? WOOD_TORSO : WOOD));
}
// joint pegs
ctx.fillStyle = EDGE;
for (const c of m.joints) {
const p = worldPoint(c.bodyA, c.pointA);
ctx.beginPath();
ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
ctx.fill();
}
}
canvas.style.cursor = grabbed ? "grabbing" : "grab";
if (grabbed) hint = Math.max(0, hint - 0.05);
if (hint > 0) {
ctx.globalAlpha = hint * 0.55;
ctx.fillStyle = "#3d3224";
ctx.font = "15px sans-serif";
ctx.textAlign = "center";
ctx.fillText("Drag me, then let go to throw!", W / 2, H - 20);
ctx.globalAlpha = 1;
}
}
// ---------- Loop ----------
let last = performance.now(), acc = 0, raf;
const STEP = 1000 / 60;
function frame(now) {
acc += Math.min(now - last, 100);
last = now;
while (acc >= STEP) { Engine.update(engine, STEP); acc -= STEP; }
draw();
raf = requestAnimationFrame(frame);
}
// ---------- Resize (width: 100%) ----------
let started = false;
function resize() {
const w = Math.floor(container.clientWidth);
if (w <= 0) return;
W = w;
dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
mouse.pixelRatio = dpr;
buildWalls();
// pull any mannequin that is now outside the window back in
for (const m of mannequins) {
const x = m.torso.position.x;
const dx = x > W - 30 ? (W - 30) - x : 0;
if (dx) for (const b of m.parts) Body.translate(b, { x: dx, y: 0 });
}
if (!started) {
started = true;
spawn(W / 2, 130, 0.25, 3, 0, 0.03);
}
}
const ro = new ResizeObserver(resize);
ro.observe(container);
resetBtn.addEventListener("click", () => { clearAll(); dropOne(); });
addBtn.addEventListener("click", dropOne);
raf = requestAnimationFrame(frame);
invalidation.then(() => {
cancelAnimationFrame(raf);
ro.disconnect();
window.removeEventListener("mousemove", onWinMove);
window.removeEventListener("mouseup", onWinUp);
Events.off(engine);
Composite.clear(world, false);
Engine.clear(engine);
});
return container;
}