82 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

/*
2024-11-23 16:32:23 +03:30
* Copyright (c) Erin Catto
* Licensed under the MIT license
*/
2024-12-24 19:58:07 +03:30
import { Vec2, World, Box, RevoluteJoint, Testbed, Vec2Value, Body } from "planck";
2017-03-18 18:37:00 -04:00
2024-12-24 15:07:16 +03:30
const world = new World({
gravity: { x: 0, y: -1 },
});
2017-03-18 18:37:00 -04:00
2023-08-20 03:24:33 -07:00
const testbed = Testbed.mount();
testbed.y = -15;
testbed.width = 20;
testbed.height = 20;
testbed.start(world);
2024-12-18 14:18:45 +03:30
const DEPTH = 4;
const DENSITY = 20.0;
2024-12-24 15:07:16 +03:30
const ground = world.createBody({
type: "static",
position: { x: 0.0, y: 20.0 },
});
2024-12-18 14:18:45 +03:30
const a = 0.5;
2024-12-23 18:24:21 +03:30
const h = { x: 0.0, y: a };
2024-12-23 18:24:21 +03:30
const root = addNode(ground, { x: 0, y: 0 }, 0, 3.0, a);
world.createJoint(
2024-12-18 14:18:45 +03:30
new RevoluteJoint({
bodyA: ground,
bodyB: root,
2024-12-23 18:24:21 +03:30
localAnchorA: { x: 0, y: 0 },
2024-12-18 14:18:45 +03:30
localAnchorB: h,
}),
);
2024-12-24 19:58:07 +03:30
function addNode(parent: Body, localAnchor: Vec2Value, depth: number, offset: number, a: number) {
2024-12-23 18:24:21 +03:30
const h = { x: 0.0, y: a };
2024-12-18 14:18:45 +03:30
const node = world.createBody({
type: "dynamic",
position: new Vec2(parent.getPosition()).add(localAnchor).sub(h),
});
2024-12-24 19:58:07 +03:30
node.createFixture({
shape: new Box(0.25 * a, a),
density: DENSITY,
});
if (depth === DEPTH) {
2023-08-14 13:59:23 -07:00
return node;
}
2018-10-20 23:34:22 -07:00
2024-12-23 18:24:21 +03:30
const left = { x: offset, y: -a };
const right = { x: -offset, y: -a };
2024-12-18 14:18:45 +03:30
const leftChild = addNode(node, left, depth + 1, 0.5 * offset, a);
const rightChild = addNode(node, right, depth + 1, 0.5 * offset, a);
2018-10-20 23:34:22 -07:00
world.createJoint(
2024-12-18 14:18:45 +03:30
new RevoluteJoint({
bodyA: node,
bodyB: leftChild,
localAnchorA: left,
localAnchorB: h,
}),
);
world.createJoint(
2024-12-18 14:18:45 +03:30
new RevoluteJoint({
bodyA: node,
bodyB: rightChild,
localAnchorA: right,
localAnchorB: h,
}),
);
2023-08-14 13:59:23 -07:00
return node;
}