0

我遇到了增量/经过时间的问题。

当窗口模糊时,循环会正确暂停。

如果您等待几秒钟并重新单击窗口(焦点),则经过的时间从较高的数字开始,然后重置为 0。

当窗口模糊时,如何阻止经过时间增加?这个较高的数字会影响我的动画并使其运行得太快,直到增量再次正确为止。

我已经设置了一个示例循环。您可以在控制台中看到我的意思: 示例

if (window.requestAnimationFrame !== undefined) {
    window.requestAnimFrame = (function () {
        'use strict';

        return window.requestAnimationFrame ||
               window.webkitRequestAnimationFrame ||
               window.oRequestAnimationFrame ||
               window.mozRequestAnimationFrame ||
               function (callback) {
                    window.setTimeout(callback, 1000 / 60); //Should be 60 FPS
               };
    }());
}

(function () {
    'use strict';

    var elapsed,
        isPaused = false,
        lastTime = 0,
        loop,
        setElapsed,
        startTime = 0,
        update;

    //Set the elapsed time
    setElapsed = function () {
        startTime = Date.now();
        elapsed = startTime - lastTime; //Calculate the elapsed time since the last frame. Dividing by 1000 turns it to seconds
        lastTime = startTime;
    };

    update = function () {
        //Update the animation etc.
        console.log('animation');
    };

    loop = function () {
        setElapsed();
        update(elapsed);    

        console.log('elapsed: ' + elapsed);

        requestAnimFrame(function () {
            if (isPaused === false) {
                loop();
            } 
        }); //Re-loop constantly using callback window.setTimeout(callback, 1000 / 60); //Should be 60 FPS

    };

    //When the window blurs, pause it
    window.onblur = function () {
        isPaused = true; //Pause the game
    };

    //When the window is in focus, resume it
    window.onfocus = function () {
        isPaused = false;
        loop(); //Re-init the game
    };

    loop();

}());

谢谢

4

1 回答 1

1

elapsed赋值(setElapsed函数内部)lastTime只应在后者非零时使用。否则它应该设置为 0(这意味着第一次调用)。

此外,您必须重置lastTime到事件发生0的时间。onblur

setElapsed = function () {
    startTime = Date.now();
    elapsed = lastTime? startTime - lastTime : 0;
    lastTime = startTime;
};
...
window.onblur = function () {
    isPaused = true; // Pause the game
    lastTime = 0; // reset lastTime
};
于 2015-04-04T18:51:51.593 回答