planck-deterministic/example/VerticalStack.ts

106 lines
2.0 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-23 18:24:21 +03:30
import { World, Body, Edge, Circle, Box, Testbed } from "planck";
2024-12-18 14:18:45 +03:30
const world = new World({
2024-12-23 18:24:21 +03:30
gravity: { x: 0, y: -10 },
blockSolve: true,
});
2023-08-20 03:24:33 -07:00
const testbed = Testbed.mount();
testbed.info("X: Launch a bullet");
testbed.start(world);
2023-08-14 13:59:23 -07:00
const columnCount = 3;
const rowCount = 20;
2024-12-18 14:18:45 +03:30
let bullet: Body | null = null;
const bodies: Body[] = [];
const indices: number[] = [];
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 }),
});
ground.createFixture({
shape: new Edge({ x: 20.0, y: 0.0 }, { x: 20.0, y: 20.0 }),
});
2024-12-18 14:18:45 +03:30
const xs = [0.0, -10.0, -5.0, 5.0, 10.0];
2024-12-18 14:18:45 +03:30
const shape = new Box(0.5, 0.5);
2023-08-14 13:59:23 -07:00
for (let j = 0; j < columnCount; ++j) {
for (let i = 0; i < rowCount; ++i) {
2024-12-18 14:18:45 +03:30
const n = j * rowCount + i;
indices[n] = n;
2024-12-18 14:18:45 +03:30
const x = 0.0;
2023-08-14 13:59:23 -07:00
// let x = Math.random() * 0.04 - 0.02;
// let x = i % 2 == 0 ? -0.01 : 0.01;
2024-12-24 15:07:16 +03:30
const body = world.createBody({
type: "dynamic",
userData: indices[n],
position: { x: xs[j] + x, y: 0.55 + 1.1 * i },
});
2024-12-24 19:58:07 +03:30
body.createFixture({
shape: shape,
density: 1.0,
friction: 0.3,
});
bodies[n] = body;
}
}
testbed.keydown = function (code, char) {
switch (char) {
case "X":
2024-12-24 15:07:16 +03:30
fireBullet();
break;
case "Z":
2024-12-18 14:18:45 +03:30
// @ts-expect-error
world.m_blockSolve = !world.m_blockSolve;
break;
}
};
2023-08-14 13:59:23 -07:00
let stepCount = 1;
testbed.step = function () {
2024-12-18 14:18:45 +03:30
// @ts-expect-error
testbed.status("Blocksolve", world.m_blockSolve);
2023-08-14 13:59:23 -07:00
if (stepCount++ % 300 == 0) {
2024-12-24 15:07:16 +03:30
fireBullet();
}
};
2023-08-14 13:59:23 -07:00
2024-12-24 15:07:16 +03:30
function fireBullet() {
if (bullet != null) {
world.destroyBody(bullet);
bullet = null;
}
2023-08-14 13:59:23 -07:00
2024-12-24 15:07:16 +03:30
bullet = world.createBody({
type: "dynamic",
bullet: true,
position: { x: -31.0, y: 5.0 },
linearVelocity: {
2024-12-23 18:24:21 +03:30
x: 400.0,
y: Math.random() * 100 - 50,
2024-12-24 15:07:16 +03:30
},
});
bullet.createFixture({
shape: new Circle(0.25),
density: 20.0,
restitution: 0.05,
});
}