Bash.tv → GitHub → itch.io

Make sounds come from where things are in the game: in 2D, pan left and right by position relative to the camera and fade with distance (with a hearing range so far sounds don't even start), sounds that follow moving objects, muffling behind walls on tile maps; in 3D, PannerNodes with HRTF and a listener that follows the camera (three.js or your own). Includes a positional audio module on top o...

Download skill (.zip) Files on GitHub

Spatial game audio

2D games

import { createEngine } from "./engine.js";
import { createSpatial2D, tileOccluder } from "./spatial.js";     // assets/spatial.js (engine.js is included)
const space = createSpatial2D(engine, { hearing: 900, to: mixer.bus("sfx") });
// every frame:
space.listener(camera.x + camera.w / 2, camera.y + camera.h / 2);
space.update();
// events:
space.play("explosion", { x: e.x, y: e.y });
space.play("engine", { loop: true, follow: () => (ship.alive ? ship : null) });   // stops when follow returns null
space.play("drip", { x, y, occluded: tileOccluder((tx, ty) => map.solid(tx, ty), 32) });
Option Default Meaning
hearing 1000 distance where a sound reaches silence; beyond it one-shots don’t start
near 15% of hearing full volume inside this
panWidth 60% of hearing sideways distance for full pan
maxPan 0.85 never fully in one ear

Set hearing to about one and a half screen widths, so players hear what’s just off screen. The player’s own sounds (jump, shoot) shouldn’t be positional: play them centered.

3D games

import { createSpatial3D } from "./spatial.js";
const space3 = createSpatial3D(engine, { to: mixer.bus("sfx") });
space3.fromCamera(camera);       // three.js camera, every frame (or listener(x, y, z, fx, fy, fz))
space3.update();
space3.play("growl", { follow: () => monster.position, near: 2, far: 40 });

HRTF sounds best on headphones and costs more; use hrtf: false for many sounds at once or on slow phones.

Pitfalls

Positional sound for the player’s own actions, a hearing range smaller than the screen, 100% pan on headphones, forgetting update() (sounds stay where they started), and dozens of HRTF panners on phones.