多次单击按钮使游戏 运行 越来越快 - javascript

click button sevral times make the game run faster and faster - javascript

作为学习的一部分,我使用 canvas 在 javascript 中构建游戏 "Space Invaders"。 在游戏开始之前,主页面已加载并等待点击新游戏按钮。当我点击这个按钮时,游戏开始 运行 正常并且没有任何问题。 (游戏 运行s 通过调用函数 update() 和 render() 的递归函数 - 参见代码 - ...) 当我在游戏 运行 期间再次按下此按钮时,问题就来了。发生的事情是游戏 运行 更快,当我多次点击它时游戏 运行 越来越快......

我现在不知道是不是因为间隔的循环本身不明确,或者可能是因为 运行() 函数再次调用自身并导致循环到递归函数中。

非常感谢。

//------------------------------------// //当我按下新游戏按钮时调用此函数

    function startGame()
    {   
        clearInterval(timeInterval);
        run();
        // run function - run the recursive function below
        timeInterval = setInterval(randEnemyShots,frequencyShot);
        // randEnemyShots function - choose one enemey from all enemies to shot 
        // frequencyShot variable - this is the frequqncy of shots 
    }

//------------------------------------//

    function run()
    {
        var loop=function(){
            if(gameRuning)
            {
                update(); 
                // update function - all the logic of game
                render();
                // render function - drawing the game 
                window.requestAnimationFrame(loop,canvas);
            }
        };
        window.requestAnimationFrame(loop,canvas);
    }

//---------------------------------------- ---------------------------------------------- --------------------------//

最好使用 setTimeout(带检查)而不是 setInterval。由于 setInterval 的行为和成本通常很奇怪。

问题是,当您单击 'Start' 按钮时,您会再次调用 run() 函数,这实际上使游戏速度加倍。

run()函数应该在游戏初始化时只调用一次,这样游戏循环就可以运行无限期。

function gameInit(){
    //Initialisation code here
    run(); //Start the game loop only once
}

function startGame() {   
    //Handle 'Start' button click
    clearInterval(timeInterval);
    timeInterval = setInterval(randEnemyShots,frequencyShot);
}

如果设置为 false,则可以将 gameRuning 值用于 'pause' 循环。