我正在用 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;
滞后又回来了!现在我确定播放声音会导致问题。我对么?为什么会这样?我如何解决它?