Я пытаюсь воспроизвести случайный аудиоклип в игре, которую делаю в Phaser 3. Я хочу воспроизвести любое из следующих событий, когда произойдет определенное событие:
audioBanshee0 = this.sound.add('audioBanshee0',{volume: 0.5});
audioBanshee1 = this.sound.add('audioBanshee1',{volume: 0.5});
audioBanshee2 = this.sound.add('audioBanshee2',{volume: 0.5});
audioBanshee3 = this.sound.add('audioBanshee3',{volume: 0.5});
audioBanshee4 = this.sound.add('audioBanshee4',{volume: 0.5});
Я пробовал следующее:
var ref = Math.floor(Math.random() * Math.floor(5));
const audioBansheeScreech = "audioBanshee" + ref;
audioBansheeScreech.play();
я получаю сообщение об ошибке
audioBansheeScreech.play()
is not a function
потому что audioBansheeScreech
это строка. Я могу обойти это с помощью циклов for и операторов if, но я бы предпочел избегать.
Не знаю о фазере, но вам, вероятно, следует создать массив audioBanshee
. Тогда получите рандом с помощью array[ref]
спасибо, Алекс, попробовал, я получаю другую ошибку.. похоже, мне придется идти в этом направлении, адига... просто подумал, что может быть трюк в java-скрипте. Спасибо
Их может быть проще переместить в объект, тогда вы можете вызывать их с помощью строки:
const audioBanshees = {
audioBanshee0: this.sound.add('audioBanshee0',{volume: 0.5}),
audioBanshee1: this.sound.add('audioBanshee1',{volume: 0.5}),
audioBanshee2: this.sound.add('audioBanshee2',{volume: 0.5}),
audioBanshee3: this.sound.add('audioBanshee3',{volume: 0.5}),
audioBanshee4: this.sound.add('audioBanshee4',{volume: 0.5})
}
let ref = Math.floor(Math.random() * Math.floor(5));
const audioBansheeScreech = audioBanshees["audioBanshee" + ref];
audioBansheeScreech.play()
Хотя IMO, массив здесь был бы более логичным и легким для чтения:
const audioBanshees = [
this.sound.add('audioBanshee0',{volume: 0.5}),
this.sound.add('audioBanshee1',{volume: 0.5}),
this.sound.add('audioBanshee2',{volume: 0.5}),
this.sound.add('audioBanshee3',{volume: 0.5}),
this.sound.add('audioBanshee4',{volume: 0.5})
]
let ref = Math.floor(Math.random() * Math.floor(5));
const audioBansheeScreech = audioBanshees[ref];
audioBansheeScreech.play()
почему вы говорите логичнее?
Только потому, что здесь мы хотим хранить и получать доступ к плоскому списку значений, используя случайный индекс в качестве идентификатора. Для этой задачи больше подходит массив, а не объект (ИМО), но оба метода будут работать.
попробуй
this.sound.add("audioBanshee" + ref, { volume: 0.5 }).play()