117 lines
2.4 KiB
TypeScript
Raw Permalink Normal View History

/*
2024-11-23 16:32:23 +03:30
* Copyright (c) Erin Catto
* Licensed under the MIT license
*/
// This is used to test sensor shapes.
import { World, Vec2, Edge, Box, Testbed } from "planck";
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.start(world);
2024-12-18 14:18:45 +03:30
let breakVelocity: Vec2;
let breakAngularVelocity: number;
2023-08-14 13:59:23 -07:00
let broke = false;
// Ground body
2024-12-24 15:07:16 +03:30
const ground = world.createBody({
type: "static",
});
2024-12-24 19:58:07 +03:30
ground.createFixture({
shape: new Edge({ x: -40.0, y: 0.0 }, { x: 40.0, y: 0.0 }),
density: 0.0,
});
// Breakable dynamic body
2024-12-24 15:07:16 +03:30
const body1 = world.createBody({
type: "dynamic",
position: { x: 0.0, y: 40.0 },
angle: 0.25 * Math.PI,
});
2024-12-23 18:24:21 +03:30
const shape1 = new Box(0.5, 0.5, { x: -0.5, y: 0.0 }, 0.0);
2024-12-24 19:58:07 +03:30
const piece1 = body1.createFixture({
shape: shape1,
density: 1.0,
});
2024-12-23 18:24:21 +03:30
const shape2 = new Box(0.5, 0.5, { x: 0.5, y: 0.0 }, 0.0);
2024-12-24 19:58:07 +03:30
let piece2 = body1.createFixture({
shape: shape2,
density: 1.0,
});
world.on("post-solve", function (contact, impulse) {
if (broke) {
// The body already broke.
return;
}
// Should the body break?
2024-12-18 14:18:45 +03:30
const count = contact.getManifold().pointCount;
2023-08-14 13:59:23 -07:00
let maxImpulse = 0.0;
for (let i = 0; i < count; ++i) {
maxImpulse = Math.max(maxImpulse, impulse.normalImpulses[i]);
}
if (maxImpulse > 40.0) {
2025-06-05 22:53:16 +03:30
setTimeout(() => {
broke = true;
breakIt();
});
}
});
2024-12-24 17:41:58 +03:30
function breakIt() {
// Create two bodies from one.
2024-12-18 14:18:45 +03:30
const center = body1.getWorldCenter();
body1.destroyFixture(piece2);
2024-12-24 15:07:16 +03:30
const body2 = world.createBody({
type: "dynamic",
position: body1.getPosition(),
angle: body1.getAngle(),
});
2024-12-24 19:58:07 +03:30
piece2 = body2.createFixture({
shape: shape2,
density: 1.0,
});
// Compute consistent velocities for new bodies based on
// cached velocity.
2024-12-18 14:18:45 +03:30
const center1 = body1.getWorldCenter();
const center2 = body2.getWorldCenter();
2024-12-18 14:18:45 +03:30
const velocity1 = Vec2.add(
breakVelocity,
Vec2.cross(breakAngularVelocity, Vec2.sub(center1, center)),
);
2024-12-18 14:18:45 +03:30
const velocity2 = Vec2.add(
breakVelocity,
Vec2.cross(breakAngularVelocity, Vec2.sub(center2, center)),
);
body1.setAngularVelocity(breakAngularVelocity);
body1.setLinearVelocity(velocity1);
body2.setAngularVelocity(-breakAngularVelocity);
body2.setLinearVelocity(velocity2);
}
testbed.step = function () {
// Cache velocities to improve movement on breakage.
if (!broke) {
breakVelocity = body1.getLinearVelocity();
breakAngularVelocity = body1.getAngularVelocity();
}
};