avocado-old/packages/sound/traits/audible.trait.js
2020-06-19 22:01:45 -05:00

105 lines
1.8 KiB
JavaScript

import {Trait} from '@avocado/entity';
import {Sound} from '..';
export default class Audible extends Trait {
static behaviorContextTypes() {
return {
hasSound: {
type: 'bool',
label: 'Has $1 sound',
args: [
['key', {
type: 'string',
}],
],
},
playSound: {
type: 'void',
label: 'Play the $1 sound.',
args: [
['key', {
type: 'string',
}],
],
},
};
}
static defaultParams() {
return {
sounds: {},
};
}
static describeParams() {
return {
sounds: {
type: 'object',
label: 'Sounds',
},
};
}
static type() {
return 'audible';
}
hydrate() {
if (AVOCADO_CLIENT) {
this.loadSounds();
}
}
constructor(entity, params, state) {
super(entity, params, state);
this._sounds = this.params.sounds;
this.sounds = {};
}
destroy() {
for (const key in this.sounds) {
const sound = this.sounds[key];
sound.release();
}
}
loadSounds() {
const keys = Object.keys(this._sounds);
const soundPromises = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const soundJSON = this._sounds[key];
soundPromises.push(Sound.load(soundJSON.uri));
}
const soundsPromise = Promise.all(soundPromises);
soundsPromise.then((sounds) => {
for (let i = 0; i < sounds.length; i++) {
const key = keys[i];
const sound = sounds[i];
this.sounds[key] = sound;
}
});
}
methods() {
return {
hasSound: (key) => {
return !!this.sounds[key];
},
playSound: (key) => {
const sound = this.sounds[key];
if (!sound) {
return;
}
sound.play();
},
};
}
}