Skip to content
1        10        20        30        40        50        60        70        801import { blockedAt, groundAt } from './city.js';2import { NEST } from './config.js';34export const EYE = 1.65;5const RADIUS = 0.3;6const WALK = 2.8;7const SPRINT = 5.4;89export class Player {10  constructor(camera, scene) {11    this.camera = camera;12    this.eye = EYE;13    camera.rotation.order = 'YXZ';14    scene.add(camera);15    this.teleport(NEST);16  }1718  // Puts the player on a spot: {x, z, feet, yaw}. A map's spawn or the street's nest.19  teleport(spot) {20    this.x = spot.x;21    this.z = spot.z;22    this.feet = spot.feet;23    this.viewFeet = spot.feet;24    this.yaw = spot.yaw;25    this.pitch = 0;26  }2728  look(dx, dy, sens) {29    this.yaw -= dx * sens;30    this.pitch = Math.max(-1.45, Math.min(1.45, this.pitch - dy * sens));31  }3233  move(dt, keys, sprintHeld) {34    let f = 0;35    let r = 0;36    if (keys.KeyW) f += 1;37    if (keys.KeyS) f -= 1;38    if (keys.KeyD) r += 1;39    if (keys.KeyA) r -= 1;40    const moving = f !== 0 || r !== 0;41    const sprinting = moving && sprintHeld && f >= 0;42    if (moving) {43      const len = Math.hypot(f, r);44      f /= len;45      r /= len;46      const speed = (sprinting ? SPRINT : WALK) * dt;47      const fx = -Math.sin(this.yaw);48      const fz = -Math.cos(this.yaw);49      const rx = Math.cos(this.yaw);50      const rz = -Math.sin(this.yaw);51      const dx = (fx * f + rx * r) * speed;52      const dz = (fz * f + rz * r) * speed;53      const nx = this.x + dx;54      if (!blockedAt(nx, this.z, RADIUS, this.feet, this.feet + 1.8)) this.x = nx;55      const nz = this.z + dz;56      if (!blockedAt(this.x, nz, RADIUS, this.feet, this.feet + 1.8)) this.z = nz;57    }58    this.feet = groundAt(this.x, this.z, this.feet);59    // Ease the camera over stair treads so each step doesn't snap the view.60    this.viewFeet += (this.feet - this.viewFeet) * Math.min(1, dt * 12);61    return { moving, sprinting };62  }6364  applyCamera(pitchAdd = 0, yawAdd = 0) {65    const c = this.camera;66    c.position.set(this.x, this.viewFeet + this.eye, this.z);67    c.rotation.x = this.pitch + pitchAdd;68    c.rotation.y = this.yaw + yawAdd;69  }70}