Biome und Vegetation auf Voxel-Terrain in Babylon.js · Teil 12 von 12 der Serie
Teil 12: Bäume fällen
Gib der Spielfigur eine Axt. Ein Baum, der vier Hiebe bekommt, verlässt den Wald und fällt als starrer Körper, zerschlägt die Blöcke, die er trifft, landet, wirft sein Laub ab und liegt als fester Stamm, den die Axt zerhackt. Auch Bäume, deren Boden weggegraben wird, fallen.
Biome und Vegetation auf Voxel-Terrain in Babylon.jsTeil 12 von 12
Auf dieser Seite
Quest-Ziele
- Mit einem Strahl gegen Zylinder auf einen Stamm zielen, ohne Meshes zu picken
- Einzelne Bäume aus einem Wald nehmen, den eine Regel pflanzt
- Aus Stamm und Krone einen starren Körper für einen Baum bauen
- Nur das Holz eines Baums zeichnen, indem weniger Indizes gezeichnet werden
- Einen liegenden Stamm fest machen und ihn zerhacken
- Die Bäume fällen, deren Boden weggegraben wird
Der Wald steht, wiegt sich und reicht bis zum Horizont, und nichts, was du tust, verändert ihn. Dieser letzte Teil gibt dir eine Axt. Vier Hiebe fällen einen Baum: Er kippt von dir weg, fällt als starrer Körper, von derselben Art, als die die Mauern der Bau-Serie fallen, zerschlägt die Blöcke, auf denen er landet, wirft sein Laub ab und liegt als Stamm. Der Stamm ist fest, du kannst auf ihm stehen, und die Axt zerhackt ihn. Und ein Baum braucht Boden: Grab ihn weg, und der Baum kommt auch herunter.
Holz und Laub getrennt
Ein liegender Stamm ist ein Baum ohne Blätter. Ein zweites Mesh braucht es dafür nicht: meshTree() macht zuerst alle Röhren und danach alle Karten, also sind die ersten Indizes des Meshes das Holz und der Rest das Laub. Ein Mesh, von dem nur die ersten soundso vielen Indizes gezeichnet werden, ist der kahle Baum aus Teil 7. Das Modell muss sich merken, wo das Holz endet. In src/trees.ts bekommt TreeModel ein Feld, und meshTree() notiert die Zahl, kurz bevor es die Blattzweige macht:
/** How many of the mesh's indices are its wood: they come first, the leaves after them. */
wood: number;
const wood = indices.length;Ergänze in dem Objekt, das meshTree() zurückgibt, wood, vor girth.
Bäume, die weg sind
Der Wald führt keine Liste von Bäumen, aus der man einen herausnehmen könnte. Seine Bäume kommen aus einer Regel: Eine Kachel, die verworfen und neu gepflanzt wird, kommt mit jedem Baum zurück, den die Regel ihr gibt. Fällen kann also nichts löschen. Stattdessen führt der Wald eine Liste der Bäume, die weg sind, und lässt sie überall aus, wo er mit Bäumen umgeht.
Dafür braucht ein Baum einen Namen, der jedes Mal derselbe ist, wenn seine Kachel gepflanzt wird. Die Regel aus Teil 9 erlaubt einen Baum pro Zelle von 6 m, also benennt ihn die Zelle, in der er steht, und die Zelle folgt aus dem Ort des Baums: Der Worker muss nichts Neues schicken. Importiere in src/forest.ts auch TREE_CELL aus ./treeRule.ts und ergänze nach tileKey:
/** A tree that stands: its numbers from the list, and a key that no other tree has. */
export interface StandingTree {
x: number;
y: number;
z: number;
size: number;
turn: number;
model: number;
key: number;
}
/** A tree's key: the number of its cell, which holds no other tree. */
const keyOf = (x: number, z: number) => (Math.floor(x / TREE_CELL) + 32768) * 65536 + Math.floor(z / TREE_CELL) + 32768;
function standing(trees: Float32Array, t: number): StandingTree {
return { x: trees[t], y: trees[t + 1], z: trees[t + 2], size: trees[t + 3], turn: trees[t + 4], model: trees[t + 6], key: keyOf(trees[t], trees[t + 2]) };
}StandingTree ist ein Baum, wie ihn der Rest des Spiels sieht: eine Zeile aus der Liste der Kachel, mit Namen für ihre Zahlen. Die Klasse Forest bekommt die Liste der Gefällten als Feld: private readonly gone = new Set<number>();. Die Karten aus Teil 10 können Bäume schon auslassen. Ersetze card():
/** Makes a tile's cards, anew if it had some. */
private card(tile: Tile): void {
tile.cards?.dispose();
tile.cards = null;
const { trees } = tile;
if (!trees || !this.cardMaterial) return;
tile.cards = createCards(this.scene, trees, this.models, this.cardMaterial, (t) => this.gone.has(keyOf(trees[t], trees[t + 2])));
}Ergänze danach drei Methoden:
/** Takes a tree out of the forest: it is drawn no more, and its trunk is not solid. */
fell(tree: StandingTree): void {
this.gone.add(tree.key);
this.sorted = null;
const tile = this.tiles.get(tileKey(Math.floor(tree.x / TILE), Math.floor(tree.z / TILE)));
if (tile) this.card(tile);
}
/** The trees that stand around a point, within `reach` meters along the ground. */
around(x: number, z: number, reach: number): StandingTree[] {
const found: StandingTree[] = [];
for (let cellZ = z - reach; cellZ < z + reach + GRID; cellZ += GRID) {
for (let cellX = x - reach; cellX < x + reach + GRID; cellX += GRID) {
const tile = this.tiles.get(tileKey(Math.floor(cellX / TILE), Math.floor(cellZ / TILE)));
if (!tile?.trees) continue;
const { trees } = tile;
tile.grid ??= gridOf(trees);
for (const t of tile.grid.get(gridKey(cellX, cellZ)) ?? []) {
if (Math.hypot(trees[t] - x, trees[t + 2] - z) <= reach && !this.gone.has(keyOf(trees[t], trees[t + 2]))) found.push(standing(trees, t));
}
}
}
return found;
}
/** The tree whose trunk a ray hits first, and how far along the ray. */
pick(origin: Vector3, direction: Vector3, reach: number): { tree: StandingTree; distance: number } | null {
let nearest: { tree: StandingTree; distance: number } | null = null;
for (const tree of this.around(origin.x, origin.z, reach + 1)) {
const model = this.models[tree.model];
const radius = model.girth * tree.size;
// Seen from above, the trunk is a circle and the ray a line: where the line enters the circle.
const [dx, dz] = [direction.x, direction.z];
const [ox, oz] = [origin.x - tree.x, origin.z - tree.z];
const a = dx * dx + dz * dz;
const b = ox * dx + oz * dz;
const inside = b * b - a * (ox * ox + oz * oz - radius * radius);
if (a === 0 || inside < 0) continue;
const distance = (-b - Math.sqrt(inside)) / a;
// And there the ray has to be at the trunk's height.
const height = origin.y + direction.y * distance - tree.y;
if (distance < 0 || distance > reach || height < 0 || height > model.height * tree.size * TRUNK) continue;
if (!nearest || distance < nearest.distance) nearest = { tree, distance };
}
return nearest;
}fell()setzt einen Baum auf die Liste, lässt die Meshes beim nächsten Update neu sortieren und macht die Karten der Kachel des Baums neu, ohne den Baum.around()findet die Bäume nahe einem Punkt, über das Gitter, das Teil 9 für die Stämme gebaut hat. Graben und Zielen fragen beide danach.pick()findet den Stamm, den ein Strahl trifft. Babylon.js kann das nicht: Es pickt Meshes, und der Wald hat ein Mesh pro Modell, an tausend Stellen gezeichnet, die nur die Grafikkarte kennt. Aber ein Stamm ist ein stehender Zylinder, und ein Strahl gegen einen Zylinder ist Schulgeometrie. Von oben gesehen ist der Stamm ein Kreis und der Strahl eine Gerade. Wo die Gerade in den Kreis eintritt, ist die kleinere Lösung einer quadratischen Gleichung, und wenn der Strahl in dieser Entfernung zwischen dem Fuß des Baums und seiner Krone ist, trifft er den Stamm.
Zwei Stellen bleiben, die mit Bäumen umgehen. Ergänze in sort() nach der Zeile, die Bäume außer Reichweite überspringt, und in nearest() nach der Zeile, die die Höhe prüft: if (this.gone.has(keyOf(trees[t], trees[t + 2]))) continue;. Ein gefällter Baum wird nicht mehr gezeichnet, und sein Stamm ist nicht fest.
Ein fallender Baum
Was fällt, ist ein Body, der starre Körper aus Teil 7 der Bau-Serie. Er will zwei Dinge: Teile, jedes mit einer Masse, einer Mitte und einer Trägheit, und Punkte, mit denen er die Welt berührt. Für ein Stück Mauer kamen die aus seinen Blöcken. Für einen Baum kommen sie aus seinen Maßen:
Der Stamm wird in sechs Scheiben geschnitten. Jede ist ein Teil, so schwer wie ein Zylinder aus frischem Holz ihrer Größe, und jede hat vier Punkte um ihr unteres Ende. Sechs kleine Teile in einer Reihe haben fast die Trägheit eines langen Stabs, und die macht den Baum schwer um seinen Fuß zu drehen und leicht um seinen Stamm.
Die Krone ist ein weiteres Teil: leicht, drei Zehntel des Gewichts des Stamms, aber weit oben. Sechs Punkte um sie, ein gutes Stück innerhalb ihrer Reichweite, verhindern, dass der Baum flach auf seinem Stamm liegt: Er kommt auf seinen Ästen zur Ruhe, wie Bäume es tun.
Der eigene Rahmen des Körpers hat seinen Ursprung am Fuß des Baums, mit dem Stamm gerade nach oben. Damit der Baum umkippt, beginnt der Körper mit einer Drehung um die waagrechte Achse, die quer zu der Richtung liegt, in die er fallen soll. Die Punkte um seinen Fuß greifen durch Reibung in den Boden, der Stamm dreht sich über sie, und sobald das Gewicht des Baums über seinen Fuß hinaus ist, erledigt die Schwerkraft den Rest. Erstelle src/felled.ts:
import { Quaternion, TransformNode, Vector3, type Buffer, type Mesh, type Scene, type ShaderMaterial } from '@babylonjs/core/pure';
import type { Block } from './blocks.ts';
import { Body, type BodyPart } from './body.ts';
import { instanceBuffer } from './chunkPlants.ts';
import type { StandingTree } from './forest.ts';
import type { Solid, Solids, Surface } from './solids.ts';
import { createTreeMesh } from './treeMaterial.ts';
import type { TreeModel } from './trees.ts';
/** Kilograms per cubic meter of green wood. */
const WOOD = 700;
/** The trunk counts as this many parts of the body, and has a ring of points at the end of each. */
const PARTS = 6;
/** How fast a felled tree starts to tip over, in radians per second. */
const TIP = 0.6;
/** Below this height, a falling tree is gone for good. */
const BOTTOM = -500;
/**
* A felled tree: a rigid body with the tree's mesh. While it falls it is a tree; once it
* lies still it sheds its leaves and is a log, solid like a trunk that stands.
*/
export class FelledTree implements Solid {
readonly body: Body;
readonly model: TreeModel;
/** The trunk in the body's own frame: from the foot at (0, 0, 0) straight up, this long and thick. */
readonly length: number;
readonly radius: number;
isLog = false;
private readonly node: TransformNode;
private readonly mesh: Mesh;
private readonly buffer: Buffer;
constructor(scene: Scene, material: ShaderMaterial, model: TreeModel, tree: StandingTree, toward: Vector3) {
this.model = model;
const height = model.height * tree.size;
this.length = height * (model.species.leader ? 0.95 : 0.7);
this.radius = model.girth * tree.size * 0.75;
// The trunk in slices, each a part with its weight, and four points around the end
// of each to touch the world with. The crown is a part too: light, but far up.
const parts: BodyPart[] = [];
const points: Vector3[] = [];
const slice = this.length / PARTS;
for (let p = 0; p < PARTS; p += 1) {
const mass = WOOD * Math.PI * this.radius ** 2 * slice;
const inertia = (mass * slice * slice) / 6;
parts.push({ mass, center: new Vector3(0, (p + 0.5) * slice, 0), inertia: [inertia, 0, 0, 0, inertia, 0, 0, 0, inertia] });
for (const [x, z] of [[1, 0], [0, 1], [-1, 0], [0, -1]]) points.push(new Vector3(x * this.radius, p * slice, z * this.radius));
}
if (model.species.leaves) {
const crown = height * (model.species.bare + 1) * 0.5;
const reach = model.reach * tree.size * 0.6;
const mass = parts.length * parts[0].mass * 0.3;
const inertia = mass * reach * reach * 0.4;
parts.push({ mass, center: new Vector3(0, crown, 0), inertia: [inertia, 0, 0, 0, inertia, 0, 0, 0, inertia] });
// The crown touches the world with six points: it keeps the tree from lying flat.
for (const [x, y, z] of [[1, 0, 0], [-1, 0, 0], [0, 0, 1], [0, 0, -1], [0, 1, 0], [0, -0.6, 0]]) {
points.push(new Vector3(x * reach, crown + y * reach, z * reach));
}
}
this.body = new Body(parts, points);
// The body's own frame has its origin at the tree's foot.
this.body.position.addInPlace(new Vector3(tree.x, tree.y, tree.z));
// It tips over about the axis that lies across the way it falls.
this.body.spin.copyFrom(Vector3.Cross(Vector3.Up(), toward).scaleInPlace(TIP));
// The tree's own mesh, once: turned and sized as the tree was, at the origin of a
// node that follows the body, as the pieces of part 7 of the building series do.
this.mesh = createTreeMesh(scene, model, material);
this.buffer = instanceBuffer(this.mesh, new Float32Array([0, 0, 0, tree.size, tree.turn, 0, 0, tree.x * 0.37]));
this.node = new TransformNode('felled tree', scene);
this.mesh.parent = this.node;
this.mesh.position = this.body.center.negate();
this.node.rotationQuaternion = Quaternion.Identity();
this.follow();
}
/** Puts the node where the body is. */
follow(): void {
this.node.position.copyFrom(this.body.position);
this.node.rotationQuaternion!.copyFrom(this.body.orientation);
}
/** At rest it sheds its leaves: only the wood is drawn from now on. */
rest(): void {
this.isLog = true;
this.mesh.subMeshes[0].indexCount = this.model.wood;
}
/** A point of the world in the body's own frame. */
toLocal(point: Vector3): Vector3 {
return point.subtract(this.body.position).applyRotationQuaternion(this.body.orientation.conjugate()).addInPlace(this.body.center);
}
/** The nearest point of the trunk's surface to a point of the world, if within reach: the trunk is a rod with round ends. */
nearest(x: number, y: number, z: number, reach: number): Surface | null {
const point = new Vector3(x, y, z);
if (Vector3.Distance(point, this.body.position) > this.length + reach) return null;
const local = this.toLocal(point);
const onAxis = new Vector3(0, Math.min(Math.max(local.y, 0), this.length), 0);
const out = local.subtract(onAxis);
const distance = out.length() - this.radius;
if (distance >= reach) return null;
const normal = out.normalize().applyRotationQuaternion(this.body.orientation);
return { distance, normal: normal.asArray() as Surface['normal'] };
}
/** How far along a ray the trunk is hit, or null if the ray misses it. */
hit(origin: Vector3, direction: Vector3, reach: number): number | null {
for (let distance = 0; distance <= reach; distance += 0.1) {
const point = origin.add(direction.scale(distance));
if (this.nearest(point.x, point.y, point.z, 0.2)) return distance;
}
return null;
}
dispose(): void {
this.node.dispose();
this.buffer.dispose();
}
}
/** The trees that were felled: falling, or lying as logs. */
export class FelledTrees {
readonly all: FelledTree[] = [];
/** The logs, as of the last update: they are solid. */
logs: FelledTree[] = [];
/** Called with every block a falling tree hit, how fast, and the tree's mass. */
onHit: (block: Block, speed: number, mass: number) => void = () => {};
/** Called when a falling tree hits something hard: where, and how fast. */
onImpact: (point: Vector3, speed: number, tree: FelledTree) => void = () => {};
/** Called when a tree comes to rest and sheds its leaves. */
onRest: (tree: FelledTree) => void = () => {};
private readonly scene: Scene;
private readonly material: ShaderMaterial;
private readonly models: TreeModel[];
private readonly solids: Solids;
constructor(scene: Scene, material: ShaderMaterial, models: TreeModel[], solids: Solids) {
this.scene = scene;
this.material = material;
this.models = models;
this.solids = solids;
}
/** A tree that stood starts to fall `toward` a direction along the ground. */
fell(tree: StandingTree, toward: Vector3): void {
this.all.push(new FelledTree(this.scene, this.material, this.models[tree.model], tree, toward));
}
/** The log a ray hits first, and how far along the ray. */
pick(origin: Vector3, direction: Vector3, reach: number): { log: FelledTree; distance: number } | null {
let nearest: { log: FelledTree; distance: number } | null = null;
for (const log of this.logs) {
const distance = log.hit(origin, direction, reach);
if (distance !== null && (!nearest || distance < nearest.distance)) nearest = { log, distance };
}
return nearest;
}
/** Takes a log away. */
remove(tree: FelledTree): void {
tree.dispose();
this.all.splice(this.all.indexOf(tree), 1);
this.logs = this.logs.filter((other) => other !== tree);
}
/** Sets the logs near a box of the world rolling again: the ground under them may be gone. */
wakeNear(low: Vector3, high: Vector3): void {
for (const log of this.logs) {
const nearest = Vector3.Clamp(log.body.position, low, high);
if (Vector3.Distance(log.body.position, nearest) <= log.length) log.body.wake();
}
}
/** Once a frame: moves the trees that fall. */
update(dt: number): void {
for (const tree of [...this.all]) {
if (tree.body.resting) continue;
tree.body.update(dt, this.solids);
for (const [block, speed] of tree.body.hits) this.onHit(block, speed, tree.body.mass);
tree.body.hits.clear();
if (tree.body.impact) this.onImpact(tree.body.impact.point, tree.body.impact.speed, tree);
tree.body.impact = null;
tree.follow();
if (tree.body.resting && !tree.isLog) {
tree.rest();
this.onRest(tree);
}
if (tree.body.position.y < BOTTOM) this.remove(tree);
}
this.logs = this.all.filter((tree) => tree.body.resting);
}
}Das Mesh ist das des Modells, noch einmal erzeugt, mit einer einzigen Instanz im Ursprung, die die Größe und die Drehung des Baums hat. Es hängt unter einem Knoten, der dem Körper folgt, wie bei einem
Piece. Der Shader der Bäume multipliziert mitworld, das bisher die Identität war: Hier ist es die Matrix des Knotens, und der Baum dreht sich mit ihr um.rest()macht den Baum zum Stamm: Es setzt die Zahl der Indizes, die das einzige Submesh des Meshes zeichnet, aufwooddes Modells.nearest()ist die Frage des festen Körpers, für einen liegenden Stamm. Im Rahmen des Körpers ist der Stamm ein gerader Stab mit runden Enden: der nächste Punkt seiner Achse, und von dort um den Radius nach außen. Die Äste sind nicht fest. Das ist eine Vereinfachung, die du spürst, wenn du danach suchst, und sie hält die Frage billig.hit()geht in Schritten von 10 cm an einem Strahl entlang und fragtnearest(). Die Axt reicht nicht weit, das sind also ein paar Dutzend Fragen.FelledTreesist für gefällte Bäume, wasPiecesfür Stücke ist: Es bewegt die Körper, reicht weiter, was sie treffen, macht ruhende Bäume zu Stämmen und weckt Stämme, wenn sich der Boden in ihrer Nähe ändert.
Ein gefällter Baum wird vom Material der Bäume gezeichnet, mit dessen Reichweite: Weiter als 95 m von der Kamera wird er nicht gezeichnet, und er hat keine Karte. Das passt zu einem Spiel, in dem du Bäume dort fällst, wo du stehst.
Die Axt
Die Axt ist das vierte Werkzeug. In jedem Frame rechnet sie aus, worauf sie zielt: auf den nächsten Baumstamm oder liegenden Stamm in ihrer Reichweite, außer der Boden oder ein Block ist im Weg, was der Strahl der Szene selbst sagt. Ein Klick wird bis zum nächsten Frame behalten, wie es die anderen Werkzeuge tun. Ein Hieb auf einen Baum zählt hoch; der vierte fällt ihn, von der Kamera weg. Ein Hieb auf einen liegenden Stamm zerhackt ihn. Erstelle src/axe.ts:
import type { Camera, Scene, Vector3 } from '@babylonjs/core/pure';
import type { FelledTree, FelledTrees } from './felled.ts';
import type { Forest, StandingTree } from './forest.ts';
/** How far the axe reaches, in meters. */
const REACH = 4.5;
/** Blows a tree takes before it falls. */
const BLOWS = 4;
/** Fells the tree the camera looks at, blow by blow, and chops up logs. */
export class AxeTool {
/** What the axe is aimed at: a tree that stands, a log, or nothing. */
target: { tree: StandingTree } | { log: FelledTree } | null = null;
/** Blows the tree in aim still takes. */
left = BLOWS;
/** How many logs were chopped up. */
logs = 0;
/** Called with every blow, and where it lands. */
onBlow: (point: Vector3) => void = () => {};
/** Called when a tree falls, with the way it falls, and when a log is chopped up. */
onFell: (tree: StandingTree, toward: Vector3) => void = () => {};
onChop: (log: FelledTree) => void = () => {};
private swing = false;
/** The blows each tree has taken so far, by its key. */
private readonly blows = new Map<number, number>();
private readonly scene: Scene;
private readonly camera: Camera;
private readonly forest: Forest;
private readonly felled: FelledTrees;
constructor(scene: Scene, camera: Camera, forest: Forest, felled: FelledTrees) {
this.scene = scene;
this.camera = camera;
this.forest = forest;
this.felled = felled;
}
/** A click: the next update swings the axe. */
start(): void {
this.swing = true;
}
hide(): void {
this.target = null;
this.swing = false;
}
update(): void {
// What the camera looks at first: a trunk, a log, or the ground and the blocks in front of them.
const ray = this.camera.getForwardRay(REACH);
const solid = this.scene.pickWithRay(ray)?.distance || Infinity;
const tree = this.forest.pick(ray.origin, ray.direction, REACH);
const log = this.felled.pick(ray.origin, ray.direction, REACH);
const nearest = Math.min(tree?.distance ?? Infinity, log?.distance ?? Infinity);
this.target = nearest > solid ? null : tree && tree.distance === nearest ? { tree: tree.tree } : log ? { log: log.log } : null;
const swing = this.swing;
this.swing = false;
if (!this.target) return;
if ('tree' in this.target) this.left = BLOWS - (this.blows.get(this.target.tree.key) ?? 0);
if (!swing) return;
this.onBlow(ray.origin.add(ray.direction.scale(nearest)));
if ('log' in this.target) {
this.logs += 1;
this.onChop(this.target.log);
this.felled.remove(this.target.log);
return;
}
const { tree: standing } = this.target;
const blows = (this.blows.get(standing.key) ?? 0) + 1;
this.blows.set(standing.key, blows);
if (blows < BLOWS) return;
// It falls away from the one who felled it.
this.blows.delete(standing.key);
const toward = ray.direction.clone();
toward.y = 0;
this.forest.fell(standing);
this.onFell(standing, toward.normalize());
}
}Das Werkzeug entscheidet nur. Wie ein Hieb klingt und was mit einem gefällten Baum geschieht, wird ihm von außen gesagt, über onBlow, onFell und onChop.
Zusammensetzen
Importiere in src/main.ts AxeTool aus ./axe.ts und FelledTrees aus ./felled.ts. Die gefällten Bäume werden gleich nach den Stücken erzeugt, und ihre Stämme kommen zu den festen Körpern. Ersetze die Zuweisung an solids.others:
// Felled trees fall as bodies of their own, and are solid once they lie as logs.
const felled = new FelledTrees(scene, treeMaterial, treeModels, solids);
solids.others = function* () {
yield* pieces.rubble;
yield forest;
yield* felled.logs;
};Ein Baum, der auf etwas Gebautes fällt, soll damit tun, was eine fallende Mauer tut: Der Schaden aus Teil 9 der Bau-Serie nimmt ein Tempo und eine Masse, und es ist ihm gleich, wem sie gehören. Ersetze den Block, der den Schaden erzeugt und pieces.onHit setzt:
// Falling pieces and falling trees break the blocks they hit hard enough, which may let more fall.
const damage = new Damage();
let broken = 0;
pieces.onHit = felled.onHit = (block, speed, mass) => {
if (!damage.hit(block, speed, mass)) return;
blocks.store.remove(block);
crumble(middleOf(block), block, 0.8);
broken += 1;
};
// A tree lands with a thud and a puff of the ground's dust, and sheds its leaves when it lies still.
const LEAF_GREEN = '#5c8f33';
felled.onImpact = (point, speed, tree) => {
const strength = Math.min((speed - 2) / 8, 1);
dust.puff(point, '#8a7250', strength * 0.6);
sounds.thud(point, strength, Math.min(Math.max(110 / Math.cbrt(tree.body.mass / 1000), 40), 140));
};
felled.onRest = (tree) => {
if (!tree.model.species.leaves) return;
const crown = tree.body.toWorld(new Vector3(0, tree.length, 0));
dust.puff(crown, LEAF_GREEN, 1);
sounds.crack(crown, 0.5);
};Ein landender Baum schlägt dumpf auf, umso tiefer, je schwerer er ist, und wirbelt den Staub des Bodens auf. Wenn er still liegt und sein Laub verschwindet, überdecken eine grüne Wolke an seiner Spitze und ein Knacken den Moment.
Graben nimmt einem Baum den Boden. Nach jedem Edit werden die Bäume um die Box des Edits gefragt, ob ihr Fuß noch im Boden steckt: Die Dichte ein wenig über dem Fuß ist unter 0, wenn nicht. So ein Baum fällt in die Richtung, in die er zufällig gedreht ist. Ersetze world.onEdit:
world.onEdit = (box) => {
field.forget();
support.groundChanged(box);
const [low, high] = [Vector3.FromArray(box.low), Vector3.FromArray(box.high)];
pieces.wakeNear(low, high);
felled.wakeNear(low, high);
// A tree whose foot is in the air now has lost its ground, and falls.
const middle = Vector3.Center(low, high);
for (const tree of forest.around(middle.x, middle.z, Vector3.Distance(low, high) / 2)) {
if (field.probe(tree.x, tree.y + 0.3, tree.z).density >= 0) continue;
forest.fell(tree);
felled.fell(tree, new Vector3(Math.cos(tree.turn), 0, Math.sin(tree.turn)));
}
};Dort werden auch die liegenden Stämme geweckt: Ein Stamm über einem Loch rollt hinein. Jetzt das Werkzeug selbst. Ersetze die Zeile, die tool deklariert:
// And a fourth: the axe fells trees and chops up the logs they leave.
const axeTool = new AxeTool(scene, camera, forest, felled);
axeTool.onBlow = (point) => {
dust.puff(point, '#b98a52', 0.15);
sounds.knock(point, 320);
};
axeTool.onFell = (tree, toward) => {
felled.fell(tree, toward);
sounds.crack(new Vector3(tree.x, tree.y + 1, tree.z), 1);
};
axeTool.onChop = (log) => dust.puff(log.body.position, '#b98a52', 0.8);
let tool: 'terrain' | 'blocks' | 'chisel' | 'axe' = 'blocks';Die Axt hat nur eine linke Taste. Ersetze den Listener für pointerdown:
canvas.addEventListener('pointerdown', (event) => {
sounds.start();
if (document.pointerLockElement !== canvas) {
canvas.requestPointerLock();
return;
}
if (tool === 'terrain') {
if (event.button === 0) digTool.start('dig');
if (event.button === 2) digTool.start('build');
} else if (tool === 'blocks') {
if (event.button === 0) blockTool.start('break');
if (event.button === 2) blockTool.start('place');
} else if (tool === 'chisel') {
if (event.button === 0) chiselTool.start('cut');
if (event.button === 2) chiselTool.start('sharpen');
} else if (event.button === 0) {
axeTool.start();
}
});Ergänze im Listener für keydown die Taste: if (event.code === 'KeyX') tool = 'axe';. Ergänze in der Funktion des Frames nach den zwei Zeilen des Meißels:
if (tool === 'axe') axeTool.update();
else axeTool.hide();Und ergänze nach pieces.update(dt); die Zeile felled.update(dt);. Das HUD bekommt eine Zeile für die Axt, in toolLine, nach der des Meißels:
axe:
`Axe: ${axeTool.logs} logs chopped` +
(axeTool.target && 'tree' in axeTool.target
? `\n${treeModels[axeTool.target.tree.model].species.name}: ${axeTool.left} more blows`
: axeTool.target
? '\nA log: left click chops it up'
: ''),Die Hilfezeile nennt die neue Taste. Ersetze index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel biomes</title>
</head>
<body>
<canvas id="game"></canvas>
<div id="crosshair"></div>
<div id="hud"></div>
<div id="bar"></div>
<div id="help">
Click to look around · WASD walk, Shift run, Space jump · F fly (Q/E down/up) · B blocks:
left break, right place, wheel or 1–6 material, , . size · C chisel: left cut, right sharp, R round or slope ·
T terrain: left dig, right build, wheel size · X axe: left chop · M mesher · G map of the biomes · N fly to the next biome
</div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>Ausprobieren
Drück X, geh zu einer der Eichen auf der Wiese und schau auf ihren Stamm: Das HUD nennt den Baum und zählt die Hiebe, die er noch braucht. Klick viermal links. Der Baum kippt von dir weg, kommt herunter, und einen Moment, nachdem er still liegt, ist sein Laub verschwunden. Kletter auf den Stamm und zerhack ihn dann. Drück B und bau eine Mauer neben einen Baum, dann fäll den Baum auf sie. Drück T und grab unter einem anderen den Boden weg. Und drück N für den Nadelwald, wo einer fallenden Fichte andere Stämme im Weg stehen.
Wie es weitergehen kann
Das ist die Serie. Über zwölf Teile hat das Terrain der zwei früheren Serien ein Klima bekommen und sechs Biome mit eigenem Boden und eigenen Formen, ein Meer mit Ufern, Gras und kleine Pflanzen, die nach Regeln wachsen und dem weichen, was du gräbst und baust, Bäume, gewachsen aus einer Handvoll Zahlen, Wälder bis zum Horizont, Wind und eine Axt. Alles ist nach wie vor in Code gemacht, und alles folgt aus einem Seed.
Einiges lässt sie dir übrig. Gefällte Bäume könnten nachwachsen, als Schösslinge, deren Größe mit der Zeit steigt. Die Arten könnten sich mit den Jahreszeiten verfärben: Die Tönung, die jeder Baum trägt und die noch kein Shader liest, wartet auf den Herbst. Mehr Arten und mehr Sorten kleiner Pflanzen sind Zeilen in zwei Tabellen. Und das Wasser steht, wo das Land tief gemacht wurde: Wasser, das in das fließt, was du gräbst, ist eine eigene Serie.
Kommentare
Die Kommentare sind GitHub Discussions: Zum Schreiben mit GitHub anmelden.
Die Kommentare kommen über giscus von GitHub. Beim Laden gehen deine IP-Adresse an giscus.app und GitHub.
