2

ゲームが 177FPS または 22FPS で実行されている場合、プレイヤーの動きはどのように計算されますか? 私はJavascriptでこれをやろうとしています:

setInterval(update, 0);

function update() {
     player_x++;
}

問題のプレビュー

問題は、フレーム レートに応じてプレーヤーが速く/遅く動くかどうかです。どうすればこれを解決できますか?

4

3 に答える 3

2

利用可能な場合はrequestAnimationFrameを使用することを強くお勧めします (これにより、最新のブラウザーで可能な限り最高のフレーム レートが得られます)。そうでない場合は setTimeout です。次に、アニメーションが開始されてからの時間に基づいてプレーヤーの位置を決定します。

// Anonymous function used to make variables declared inside it not global
// This avoids conflicts in case variables with the same names are used
// in other scripts
(function(){

    // This checks for the requestAnimationFrame in each browser and store the first
    // it finds into requestAnimationFrame. If none are found it uses setTimeout
    // Attempting 60 frames per second.
    // It's taken from Paul Irish's blog: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    // and you can use it as is
    var requestAnimationFrame = (function(){
        return window.requestAnimationFrame    || 
               window.webkitRequestAnimationFrame || 
               window.mozRequestAnimationFrame    || 
               window.oRequestAnimationFrame      || 
               window.msRequestAnimationFrame     || 
               function(callback){
                   setTimeout(function(){ callback((new Date).getTime()); }, 1000/60);
               };
    })();

    var speed = 60; // pixels per second

    // This is used so that we only divide by 1000 once instead of every frame
    var calc = speed/1000;

    // Store the current time in start_time
    var start_time = (new Date).getTime();

    // This function is self invoking. It is wrapped in parenthesis and called immediately
    // time is passed in by requestAnimationFrame
    (function draw(time){
        // Calculate the new x position based on the current time
        var pos = (time - start_time)*calc;

        // Update the player's position
        // In my JSFiddle I update the style.left of a div
        player_x = pos;

        // Now that this frame is done request another frame.
        // draw will be called again before that frame is rendered
        requestAnimationFrame(draw);
    })();

})();

JSFiddle

于 2012-06-02T19:22:35.900 に答える
1

代わりにタイマー機能を使用してみてください。これにより、プレーヤーは時間に基づいて移動し、フレームの変化ではありません...

于 2012-06-02T19:17:11.523 に答える
1

距離は速さ(一定)と時間に等しい。フレームレート (Hz) に応じて、時間 t =1 / framerateは異なります。

これをコードに入れるには: 後続のフレーム間の時間を測定し、その時間を使用して距離を計算します。

場合によっては、バックグラウンド スレッドを用意することをお勧めします (JavaScript ではsetInterval()、提案されたとおりにCezarisLT使用し、一定の時間を使用できます。ただし、スケジュールされた時間に正確に実行されることが保証されていないため、実際には、後続の呼び出し間の時間を測定する必要がありますsetInterval()(長時間実行)関数、高い CPU 使用率)。

ところで、あなたのコードは非常に冗長で、コンパイルできません:

setInterval(update, 0)

function update() {
     player_x++;
}
于 2012-06-02T19:21:13.237 に答える