我正在尝试在Phaser 3中制作的游戏中播放随机音频剪辑。当发生特定事件时,我希望播放以下任何内容:
Task.WhenAll(tasks).Wait();
我尝试了以下方法:
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()
是一个字符串。我可以通过for循环和if语句来解决这个问题,但是我宁愿避免。
答案 0 :(得分:0)
将它们移动到对象中可能会更容易,然后可以使用字符串来调用它们:
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()