// Kinematic character body that walks on the voxel world: gravity, auto-step, walls. import * as THREE from 'three'; import type { VoxelWorld } from '../world/voxels'; export interface Bouncer { x: number; z: number; r: number; top: number; power: number; onBounce?: () => void; squash: number } export class Body { pos = new THREE.Vector3(); vel = new THREE.Vector3(); radius = 0.32; height = 1.0; grounded = false; groundY = 0; stepUp = 1.05; // can walk up one block (auto-hop) - forgiving for kids lastSafe = new THREE.Vector3(); timeSinceGround = 0; bounced = false; wading = 0; constructor(public world: VoxelWorld) {} private blockedAt(x: number, z: number, feet: number): boolean { const w = this.world, r = this.radius; for (let y = feet + 0.05; y < feet + this.height; y += 0.45) { if (w.solidAt(x + r, y, z) || w.solidAt(x - r, y, z) || w.solidAt(x, y, z + r) || w.solidAt(x, y, z - r)) return true; } return false; } private groundUnder(x: number, z: number, y: number): number { const w = this.world, r = this.radius * 0.7; return Math.max(w.groundBelow(x, z, y), w.groundBelow(x + r, z, y), w.groundBelow(x - r, z, y), w.groundBelow(x, z + r, y), w.groundBelow(x, z - r, y)); } /** Move by velocity. Returns true when a wall stopped horizontal motion. */ step(dt: number, gravity: number, bouncers: Bouncer[] = []): boolean { const p = this.pos, v = this.vel; v.y -= gravity * dt; if (v.y < -30) v.y = -30; let hitWall = false; const tryAxis = (dx: number, dz: number) => { const nx = p.x + dx, nz = p.z + dz; if (!this.world.inside(nx, nz, 0.5)) { hitWall = true; return; } if (!this.blockedAt(nx, nz, p.y)) { p.x = nx; p.z = nz; return; } // auto step: if the obstacle is low enough and we are on/near ground, climb it smoothly const g = this.groundUnder(nx, nz, p.y + this.stepUp); if ((this.grounded || this.timeSinceGround < 0.15) && g - p.y <= this.stepUp && !this.blockedAt(nx, nz, g)) { p.y = Math.max(p.y, g); p.x = nx; p.z = nz; return; } hitWall = true; }; const steps = Math.max(1, Math.ceil(Math.hypot(v.x, v.z) * dt / 0.2)); for (let s = 0; s < steps; s++) { tryAxis(v.x * dt / steps, 0); tryAxis(0, v.z * dt / steps); } const ny = p.y + v.y * dt; const g = this.groundUnder(p.x, p.z, p.y + 0.05); this.bounced = false; if (v.y <= 0 && ny <= g) { p.y = g; v.y = 0; if (!this.grounded) this.grounded = true; this.groundY = g; } else { // head bump if (v.y > 0 && this.blockedAt(p.x, p.z, ny + 0.02) && this.world.solidAt(p.x, ny + this.height, p.z)) { v.y = 0; } else p.y = ny; this.grounded = p.y <= g + 0.001; } // marshmallow trampolines for (const b of bouncers) { const dx = p.x - b.x, dz = p.z - b.z; if (dx * dx + dz * dz < b.r * b.r && p.y <= b.top + 0.05 && p.y >= b.top - 0.6 && v.y <= 0) { p.y = b.top; v.y = b.power; this.grounded = false; this.bounced = true; b.squash = 1; b.onBounce?.(); } } if (this.grounded) { this.timeSinceGround = 0; if (g > -5) this.lastSafe.copy(p); } else this.timeSinceGround += dt; return hitWall; } }