Skip to content

Spatial audio

Updated

Spatial audio makes a sound come from somewhere. A fountain in the square is loud when you stand next to it, quieter across the street, and on headphones you can tell it is on your left. This page covers the Positional Audio source, the three distance models that decide how fast a sound fades, and Audio Zones, boxes that stop the music of one room from leaking into the next.

  • Read Audio sources first. Positional Audio has every prop, method and event of the Audio component, plus the distance props on this page.
  • Zone events reach scripts through a Signal Emitter on the zone entity. See Scripting for on and EventType.

The listener is where the scene hears from. It rides the active camera, and in a headset it follows the user’s head, so what you hear always matches what you see. Positional sounds are panned with a model of how human ears receive sound from each direction (an HRTF), so on headphones a sound can come from the left, the right, in front or behind. In a headset each source turns with the head exactly as on a desktop.

The Positional Audio component (PositionalAudioComponent, comp-audio-positional) on a Positional Audio entity (PositionalAudioEntity) plays a sound file from its entity’s position. Move, parent or animate the entity and the sound moves with it: put a Positional Audio entity under a car and the engine noise follows the car.

Prop Type Default Description
src string none The sound file: a URL or an asset of the project.
volume number 1 Gain, from 0 to 1.
repeat 'once' or 'repeat' 'repeat' Play once, or loop.
autoplay boolean true Play once loaded, when the scene is active. Play mode only.
refDistance number 1 Distance in metres within which the sound is at full volume.
rolloffFactor number 1 How fast the volume falls past refDistance. Higher is faster.
maxDistance number 10000 For the linear model, the distance in metres where the sound reaches silence. The other models ignore it.
distanceModel 'inverse', 'linear' or 'exponential' 'inverse' The curve the volume follows with distance.

It has the same methods as Audio: play(), pause(), stop(), setVolume(v), isPlaying() and load(). It sends the same events as Audio under its own name: AudioPositional::ready, ::error, ::play, ::pause, ::stop and ::end, which scripts compare with EventType.AudioPositional.Ready and so on.

For the linear model, refDistance must be smaller than maxDistance.

Within refDistance every model plays at full volume. Past it, for a listener at distance d, with ref = refDistance, max = maxDistance and r = rolloffFactor:

Model Volume past refDistance Character Use it for
inverse ref / (ref + r × (d − ref)) A natural falloff that never quite reaches silence. Most sounds. It is the default.
linear 1 − r × (d − ref) / (max − ref), never below 0 Falls in a straight line to silence at maxDistance. Sounds that must stop at a known range.
exponential (d / ref) ^ −r Falls faster than inverse as r grows. Sounds that should stay very local.

Raise refDistance for loud, large sources such as a waterfall or a stage; lower it for small ones such as a ticking clock.

In the editor, a selected positional source shows a faint sphere at its refDistance.

An Audio Zone (AudioZoneEntity, with the component AudioZoneComponent, comp-audio-zone) is an invisible box that decides which positional sounds the listener hears. While the listener is inside one or more zones, it hears only the positional sources inside the same zones. Every other positional source is muted. With the listener outside every zone, or no zones in the scene, every source plays normally.

For each positional source, the rules are:

  1. A source inside a zone the listener is also in is heard.
  2. A source inside zones the listener is not in is muted: zone audio is silent from outside.
  3. A source in no zone is heard only while the listener is outside every zone.
Prop Type Default Description
halfExtents { x, y, z } { x: 1, y: 1, z: 1 } Half the box’s size along each axis, in metres, in the entity’s local space. The default is a 2 × 2 × 2 m cube. The entity’s Transform moves, rotates and scales the box.
  • Zones affect only Positional Audio and Positional Audio Tone sources. Global Audio, Audio Tone and Ambisonic sources are never muted by a zone, which makes them right for music that should play everywhere.
  • A source with an Audio Fade crossfades over the fade’s duration when a zone mutes or unmutes it. Without a Fade, it cuts.
  • A zone mute is separate from volume and from hiding: neither changes, and the source keeps playing silently.
  • Zones work in play only. In the editor a zone draws as a translucent violet box when gizmos are on.

The listener crossing the zone’s box is reported to the Signal Emitters on the zone entity:

Event EventType constant Data Sent when
AudioZone::enter EventType.AudioZone.Enter {} The listener enters the zone.
AudioZone::exit EventType.AudioZone.Exit {} The listener leaves it.

A positional radio that starts and stops when the player clicks it. While it plays, it drives away and back, so you hear the music fade to silence with distance and return.

Radio.jx
#pragma lifecycle(startup)
let sound;
let trip;
function startup() {
const radio = findEntity('Radio');
sound = findEntity('Radio Sound').getComponent(PositionalAudioComponent);
// 10 m away and back, for ever: paused until the music plays.
trip = Tween.to(radio.position, { z: radio.position.z - 10 }, {
duration: 5,
ease: Ease.InOutSine,
repeat: Infinity,
yoyo: true,
});
trip.pause();
on('radio/clicked', (event) => {
if (event.eventType !== EventType.Selectable.Select) return;
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
if (sound.isPlaying()) {
sound.pause();
trip.pause();
} else {
sound.play();
trip.resume();
}
});
}

How it works:

  • The sound entity is a child of the radio mesh, so it always plays from where the radio is, even if the radio is moved.
  • refDistance: 1.5 keeps the radio at full volume within 1.5 m. The linear model then fades it in a straight line to silence at maxDistance, 12 m, so the fade is easy to hear.
  • Pausing keeps the position, so the song continues where it stopped.
  • The trip is one endless tween whose handle is paused and resumed with the music, so the radio only travels while it plays. It starts about 2 m from you and drives past 12 m, so the music fades to silence and comes back.

Move one positional sound to each collision point and play it.

ImpactSound.jx
#pragma lifecycle(startup)
// Scene: crates with Rigid Bodies, colliders and a Signal Emitter on 'crate/hit'.
// At the scene root, a Positional Audio entity "Thud" (src: a thud, repeat: once, autoplay: off).
let thud;
let thudSound;
function startup() {
thud = findEntity('Thud');
thudSound = thud.getComponent(PositionalAudioComponent);
on('crate/hit', (event) => {
if (event.eventType !== EventType.PhysicsCollider.CollisionEnter) return;
const point = event.data.contact;
if (!point) return;
thud.position.set(point.x, point.y, point.z);
thudSound.stop();
thudSound.play();
});
}

How it works:

  • PhysicsCollider::collision-enter carries contact, the world point where the bodies touched. Because Thud sits at the scene root, its local position is a world position.
  • Moving the entity moves the sound: the thud comes from where the crates met.
  • stop() then play() restarts the one-shot. One sound entity serves every crate; when two collisions come in the same instant, the second one wins. For overlapping impacts, see the next example.

Use zone events to update a label and change the music.

RoomTracker.jx
#pragma lifecycle(startup)
const ROOM_NAMES = {
'Library Zone': 'Library',
'Workshop Zone': 'Workshop',
};
let label;
let hallMusic;
let inside = 0;
function startup() {
label = findEntity('Room Name').getComponent(UILabelComponent);
hallMusic = findEntity('Hall Music').getComponent(AudioComponent);
on('room', (event) => {
const zone = findEntity(event.entityId);
if (event.eventType === EventType.AudioZone.Enter) {
inside += 1;
label.setProps({ text: ROOM_NAMES[zone.name] ?? zone.name });
hallMusic.setVolume(0.15);
}
if (event.eventType === EventType.AudioZone.Exit) {
inside -= 1;
if (inside === 0) {
label.setProps({ text: 'Main hall' });
hallMusic.setVolume(0.6);
}
}
});
}

How it works:

  • All zones share one signal; event.entityId tells which zone sent the event, and findEntity(id) turns the id into the entity, whose name picks the room title.
  • Global Audio is never muted by zones, so the hall music keeps playing everywhere. The script lowers it inside a room instead, so the room’s own positional sounds stand out.
  • inside counts the zones the listener is in, because zones can overlap: the hall settings come back only when the listener has left them all.

1. Overlapping one-shots with spawned copies

Section titled “1. Overlapping one-shots with spawned copies”

Spawn a copy of a template sound at each footstep and remove it when it ends, so several can play at once.

Footsteps.jx
#pragma lifecycle(startup)
// Scene: a disabled Positional Audio entity "Step Template"
// (src: a footstep, repeat: once, autoplay: on) with a Signal Emitter on 'step'.
// A character script emits 'player/step' with { x, y, z } on each footstep.
function startup() {
on('player/step', (where) => {
spawn('Step Template', { position: where, enabled: true });
});
// Each copy reports its own end; remove that copy.
on('step', (event) => {
if (event.eventType === EventType.AudioPositional.End || event.eventType === EventType.AudioPositional.Error) {
destroy(event.entityId);
}
});
}

How it works:

  • spawn(name, options) copies the template entity with its components, places it at position and enables it. Because the template’s source has autoplay on, the copy plays as soon as it is active.
  • The copy keeps the template’s Signal Emitter, so every copy reports on step. event.entityId identifies which copy finished.
  • destroy(event.entityId) removes that copy and frees it. Removing on Error too keeps broken copies from piling up.
  • The template stays disabled, so it never plays itself.

Change distance props at runtime to make an alarm carry further, with a hard edge.

Siren.jx
#pragma lifecycle(startup)
// Scene: a Positional Audio entity "Siren" (src: a siren loop, autoplay: off,
// distanceModel: linear, refDistance: 2, maxDistance: 10).
// Something emits 'alarm/level' with 0 (off), 1, 2 or 3.
let siren;
function startup() {
siren = findEntity('Siren').getComponent(PositionalAudioComponent);
on('alarm/level', (level) => {
if (level === 0) {
siren.stop();
return;
}
// Level 1 reaches 10 m, level 2 reaches 25 m, level 3 reaches 60 m.
const reach = [0, 10, 25, 60][level];
siren.setProps({ distanceModel: 'linear', refDistance: 2, maxDistance: reach });
if (!siren.isPlaying()) siren.play();
});
}

How it works:

  • With the linear model the siren is at full volume within 2 m and silent exactly at maxDistance, so each level has a precise radius.
  • setProps changes the distance props on the sound that is already playing; there is no need to restart it.
  • refDistance stays below every maxDistance, as the linear model requires.
  • Using global Audio for a sound that should come from an object. Global sources do not pan or fade with distance. Use Positional Audio.
  • Setting maxDistance with the inverse model. It has no effect. Switch to linear for a hard edge, or use an Audio Zone.
  • Expecting zones to mute music. Zones never affect global Audio, Audio Tone or Ambisonic sources. Lower their volume from a script on AudioZone::enter if needed.
  • Forgetting the Signal Emitter on the zone. Zone events go to the zone entity’s own Signal Emitters.
  • Listening for Audio::end on a positional source. Positional sources send AudioPositional::… events.
  • Placing a one-shot by world position under a moved parent. entity.position is relative to the parent. Keep entities you place at world points at the scene root, or convert the point to the parent’s space.
  • Expecting zones in the editor. Zones act in play only.