我做在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;
和滞后回来了! 现在,我敢肯定,播放声音会引起问题。 我对么? 这究竟是为什么? 我如何解决它?