Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/input.ts
/**
 * Driver input from the keyboard, any standard gamepad and the on-screen touch pedals,
 * merged into one set of controls each frame.
 */

export interface Controls {
  /** +1 accelerate, -1 brake / reverse. */
  throttle: number;
  /** +1 right, -1 left. */
  steer: number;
  handbrake: boolean;
  /** One-shot presses since the last frame. */
  reset: boolean;
  camera: boolean;
  /** Into or out of the driver's seat. */
  view: boolean;
  /** First person: where to turn the head (radians, left and up positive). */
  look: { yaw: number; pitch: number };
  pause: boolean;
}

type TouchKey = 'left' | 'right' | 'gas' | 'brake' | 'drift';

export class Input {
  private readonly keys = new Set<string>();
  private readonly pressed = new Set<string>();
  private readonly touch = new Set<TouchKey>();
  private padPrev: boolean[] = [];
  private steer = 0;
  /** Head turn from dragging with the mouse; springs back when let go. */
  private mouseLook = { yaw: 0, pitch: 0, dragging: false };
  /**
   * How far dragging can turn the view: a head's turn in the driver's seat; from outside,
   * all the way round the car (no limit on yaw) and from near the ground to overhead.
   */
  lookRange = { yaw: 2.2, pitchMin: -1.1, pitchMax: 0.6 };
  /** Called on any key, click or touch (for unlocking audio). */
  onActivity: () => void = () => undefined;
  /** True once a touch has been seen. */
  touchUsed = false;

  constructor(target: HTMLElement) {
    window.addEventListener('keydown', (e) => {
      if (e.target instanceof HTMLButtonElement && (e.code === 'Space' || e.code === 'Enter')) return;
      this.onActivity();
      if (!e.repeat) this.pressed.add(e.code);
      this.keys.add(e.code);
      if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.code)) e.preventDefault();
    });
    window.addEventListener('keyup', (e) => this.keys.delete(e.code));
    window.addEventListener('blur', () => this.release());
    document.addEventListener('visibilitychange', () => this.release());
    target.addEventListener('pointerdown', (e) => {
      this.onActivity();
      // Drag on the view with the mouse to look around in first person.
      if (e.pointerType === 'mouse' && e.button === 0 && e.target instanceof HTMLCanvasElement) this.mouseLook.dragging = true;
    });
    window.addEventListener('pointermove', (e) => {
      if (!this.mouseLook.dragging) return;
      const r = this.lookRange;
      this.mouseLook.yaw = Math.max(-r.yaw, Math.min(r.yaw, this.mouseLook.yaw - e.movementX * 0.006));
      this.mouseLook.pitch = Math.max(r.pitchMin, Math.min(r.pitchMax, this.mouseLook.pitch - e.movementY * 0.006));
    });
    window.addEventListener('pointerup', () => {
      this.mouseLook.dragging = false;
      this.mouseLook.yaw = this.mouseLook.pitch = 0;
    });
  }

  /** Let go of everything (lost focus, pause). */
  release(): void {
    this.keys.clear();
    this.touch.clear();
    for (const b of document.querySelectorAll('.pedal.on')) b.classList.remove('on');
  }

  /** Wire an on-screen button to a touch control; it holds while any pointer is on it. */
  bindTouch(button: HTMLElement, key: TouchKey): void {
    const pointers = new Set<number>();
    const update = () => {
      if (pointers.size) this.touch.add(key);
      else this.touch.delete(key);
      button.classList.toggle('on', pointers.size > 0);
    };
    button.addEventListener('pointerdown', (e) => {
      e.preventDefault();
      this.touchUsed = true;
      this.onActivity();
      try {
        button.setPointerCapture(e.pointerId);
      } catch {
        // Synthetic or already-released pointers can't be captured; holding still works.
      }
      pointers.add(e.pointerId);
      update();
    });
    for (const type of ['pointerup', 'pointercancel', 'lostpointercapture'] as const)
      button.addEventListener(type, (e) => {
        pointers.delete(e.pointerId);
        update();
      });
    button.addEventListener('contextmenu', (e) => e.preventDefault());
  }

  private down(...codes: string[]): boolean {
    return codes.some((c) => this.keys.has(c));
  }

  private hit(...codes: string[]): boolean {
    return codes.some((c) => this.pressed.has(c));
  }

  read(dt: number): Controls {
    let throttle = (this.down('KeyW', 'ArrowUp') || this.touch.has('gas') ? 1 : 0) - (this.down('KeyS', 'ArrowDown') || this.touch.has('brake') ? 1 : 0);
    let target = (this.down('KeyD', 'ArrowRight') || this.touch.has('right') ? 1 : 0) - (this.down('KeyA', 'ArrowLeft') || this.touch.has('left') ? 1 : 0);
    let handbrake = this.down('Space', 'ShiftLeft', 'ShiftRight') || this.touch.has('drift');
    let reset = this.hit('KeyR');
    let camera = this.hit('KeyC');
    let view = this.hit('KeyV');
    // Q / E look left and right, F looks down at the pedals.
    let lookYaw = (this.down('KeyQ') ? 1.3 : 0) - (this.down('KeyE') ? 1.3 : 0) + this.mouseLook.yaw;
    let lookPitch = (this.down('KeyF') ? -1.0 : 0) + this.mouseLook.pitch;
    let pause = this.hit('Escape', 'KeyP');
    this.pressed.clear();

    // Gamepads: left stick or d-pad steers, right trigger gas, left trigger brake,
    // A / B / right bumper handbrake, Y reset, Back camera, right stick click first
    // person, Start pause.
    let pads: (Gamepad | null)[] = [];
    try {
      pads = navigator.getGamepads ? Array.from(navigator.getGamepads()) : [];
    } catch {
      pads = [];
    }
    const nowPressed: boolean[] = [];
    let analog = false;
    for (const pad of pads) {
      if (!pad?.connected || pad.mapping !== 'standard') continue;
      const b = (i: number) => pad.buttons[i]?.value ?? 0;
      const stick = pad.axes[0] ?? 0;
      const rx = pad.axes[2] ?? 0;
      const ry = pad.axes[3] ?? 0;
      if (Math.abs(rx) > 0.2) lookYaw -= rx * 1.4;
      if (Math.abs(ry) > 0.2) lookPitch -= ry * 0.7;
      const sx = Math.abs(stick) > 0.15 ? Math.sign(stick) * (Math.abs(stick) - 0.15) / 0.85 : 0;
      const dpad = b(15) - b(14);
      if (sx !== 0) {
        target = sx;
        analog = true;
      } else if (dpad !== 0) target = dpad;
      const t = b(7) - b(6);
      if (Math.abs(t) > 0.05) throttle = t;
      if (b(0) > 0.5 || b(1) > 0.5 || b(5) > 0.5) handbrake = true;
      for (const i of [3, 8, 9, 11]) nowPressed[i] = (nowPressed[i] ?? false) || b(i) > 0.5;
      if (b(0) > 0.5 || b(7) > 0.5) this.onActivity();
    }
    const edge = (i: number) => !!nowPressed[i] && !this.padPrev[i];
    reset ||= edge(3);
    camera ||= edge(8);
    view ||= edge(11);
    pause ||= edge(9);
    this.padPrev = nowPressed;

    // Digital steering eases in so taps make small corrections; a stick is used as is.
    if (analog) this.steer = target;
    else {
      const rate = target === 0 ? 10 : Math.sign(target) !== Math.sign(this.steer) ? 14 : 7;
      this.steer += Math.max(-rate * dt, Math.min(rate * dt, target - this.steer));
    }
    const r = this.lookRange;
    lookYaw = Math.max(-r.yaw, Math.min(r.yaw, lookYaw));
    lookPitch = Math.max(r.pitchMin, Math.min(r.pitchMax, lookPitch));
    return { throttle, steer: this.steer, handbrake, reset, camera, view, pause, look: { yaw: lookYaw, pitch: lookPitch } };
  }
}