planck-deterministic/example/MobileBalanced.ts

89 lines
1.7 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 { World, Vec2, Box, RevoluteJoint, Testbed, Body, Vec2Value } 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: -10 },
});
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(
new RevoluteJoint({
bodyA: ground,
bodyB: root,
2024-12-23 18:24:21 +03:30
localAnchorA: { x: 0, y: 0 },
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 p = new Vec2(parent.getPosition()).add(localAnchor).sub(h);
2024-12-24 15:07:16 +03:30
const node = world.createBody({
type: "dynamic",
position: p,
});
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;
}
2024-12-24 19:58:07 +03:30
node.createFixture({
shape: new Box(offset, 0.25 * a, { x: 0, y: -a }, 0.0),
density: DENSITY,
});
2024-12-23 18:24:21 +03:30
const right = { x: offset, y: -a };
const left = { x: -offset, y: -a };
2024-12-18 14:18:45 +03:30
const rightChild = addNode(node, right, depth + 1, 0.5 * offset, a);
const leftChild = addNode(node, left, depth + 1, 0.5 * offset, a);
world.createJoint(
new RevoluteJoint({
bodyA: node,
bodyB: rightChild,
localAnchorA: right,
localAnchorB: h,
}),
);
world.createJoint(
new RevoluteJoint({
bodyA: node,
bodyB: leftChild,
localAnchorA: left,
localAnchorB: h,
}),
);
2023-08-14 13:59:23 -07:00
return node;
}