2012-06-02 52 views
2

如果遊戲以177FPS或22FPS運行,玩家動作如何計算?我想這樣做在Javascript:動態FPS(每秒幀數)的玩家動作計算

setInterval(update, 0); 

function update() { 
    player_x++; 
} 

preview of problem

問題是,如果玩家將根據幀速率移動快/慢。我將如何解決這個問題?

回答

2

我強烈建議使用requestAnimationFrame可用的(這將讓你的時候最好的框架鼠e可能在現代瀏覽器中)和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

+0

這看起來像我在找什麼,但可以做成一個函數?有很多annonimius函數,我不完全確定這裏發生了什麼。你能基本上簡化這個嗎? – Kivylius

+0

@CezarisLT我會在其中添加一些評論,使其更容易理解。 – Paulpro

+0

@CezarisLT讓我知道我添加的內容是否有幫助。 – Paulpro

1

嘗試使用定時器功能代替,使得基於時間的播放器移動,而不是在幀的變化...

+0

我應該提到這一點,但我不希望有一個固定的幀速率,因爲以我的理解,這就是定時器功能做。 – Kivylius

1

的距離等於速度(常數)和時間。根據幀率(以Hz爲單位),時間t = 1/framerate將有所不同。

將此代碼放入代碼中:測量後續幀之間的時間並使用該時間計算距離。

有時一個更好的主意是有一個後臺線程(在JavaScript中,你可以使用setInterval()CezarisLT建議,並使用一定的時間。但是在實踐中,你仍然需要測量後續調用之間的時間,因爲setInterval()不能保證運行正是在預定的時間(長期運行的功能,CPU使用率過高)

BTW你的代碼過於冗長,將無法編譯:

setInterval(update, 0) 

function update() { 
    player_x++; 
}