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する必要があります。0onblur

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 に答える