我正在用 Javascript 制作一个简单的游戏,当一个物体与墙壁碰撞时,它会发出“砰”的声音。声音的响度取决于物体的速度(速度越高=>声音越大)。
播放功能:
playSound = function(id, vol) //ID of the sound in the sounds array, volume/loudness of the sound
{
if (vol) //sometimes, I just want to play the sound without worrying about volume
sounds[id].volume = vol;
else
sounds[id].volume = 1;
sounds[id].play();
}
我怎么称呼它:
playSound(2, Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV); //self.TV stands for terminal velocity. This calculates the actual speed using the basic Pythagora's theorem and then divides it by self.TV, which results in a number from 0 to self.TV. 2 is the id of the sound I want to play.
在 Chrome 中,一切运行得很好。但在 Firefox 中,每次与墙壁发生碰撞时 (=>playSound
被呼叫),有一个持续了近半秒的停顿!一开始我以为问题出在Math.sqrt
, 但是我错了。我是这样测试的:
//playSound(2, 1); //2 Is the id of the sound I want to play, and 1 is max loudness
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
这完全消除了碰撞滞后,让我相信Math.sqrt
根本不会造成任何问题。不过,为了确定一下,我这样做了:
playSound(2, 1); //2 Is the id of the sound I want to play, and 1 is max loudness
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
延迟又回来了!现在我确信播放声音会引起问题。我对么?为什么会发生这种情况?我如何解决它?