简体   繁体   English

调用requestAnimationFrame会使动画运行得更快

[英]Calling requestAnimationFrame causes animation to run faster

Press the start/restart button several times and you'll notice that the speed increases. 多次按“开始/重新启动”按钮,您会发现速度有所提高。 It's not meant to, the speed should just reset to '5'. 这并不意味着,速度应重新设置为“ 5”。 Can't figure out whats wrong. 无法找出问题所在。

http://jsfiddle.net/LQEkn/ http://jsfiddle.net/LQEkn/

The code for the start/reset button is at the bottom of the Fiddle: 开始/重置按钮的代码位于小提琴的底部:

//Start game function + button
function resetGame() {
    ball.x = board.width/2;
    ball.y = board.height/2;
    ball.xSpeed = 5;
    ball.ySpeed = 0;
    player1.score = 0;
    player1.newScore = false;
    player2.score = 0;
    player2.newScore = false;
}

startButton.onclick = function() {
    startButtonText.innerHTML = "Restart game";
    resetGame();
    renderPresentation();
    animate(step);
};

I've tried to stop the animation before calling it: 我试图在调用动画之前先停止动画:

startButton.onclick = function() {
    startButtonText.innerHTML = "Restart game";
    resetGame();
    renderPresentation();
    var rid = animate(step); //animate is window.requestAnimationFrame()
    window.cancelAnimationFrame(rid);
    animate(step);
};

I've been staring at my code for too long, anyone up to take a quick look? 我盯着我的代码已经太久了,有人可以快速浏览一下吗? Thanks! 谢谢!

The actual speed of your ball is fine. 球的实际速度很好。 However, your game runs twice as fast because every click on the restart button will call animate(step) . 但是,您的游戏运行速度快一倍,因为每次单击重新启动按钮都会调用animate(step) Since animate() is just a convenience wrapper for requestAnimationFrame you will end up with more animation/update steps than you originally intended. 由于animate()只是requestAnimationFrame的便利包装,因此最终您将获得比原先预期更多的动画/更新步骤。

The easiest solution for this is to check whether the game is already running and skip the animate(step) in this case ( fiddle ): 最简单的解决方案是检查游戏是否已经在运行,在这种情况下,跳过animate(step)小提琴 ):

startButton.onclick = function() {
    startButtonText.innerHTML = "Restart game";
    resetGame();
    renderPresentation();
    if(!game_is_running){
        animate(step);
        game_is_running = true;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM