2017-04-09 86 views
-2

我已經使用這個教程來幫助我爲我的作業寫一個簡單的JS遊戲。然而,我現在正在研究gameloop,我不知道這個特定功能是如何工作的。date.now()'then'在這裏做什麼? - Javascript

這是本教程的URL。的代碼,你要查找的塊是在8 「的遊戲主循環」 http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/

//Gameloop 
var main = function() { 
    //var with timestamp 
    var now = Date.now(); 

    //where does 'then' come from? I never declared it. 
    var delta = now - then; 

    //next up it just calls another func and provides parameter delta divided by 1000 which is the amount of miliseconds in a second 
    update(delta/1000); 
    //and it calls my render function 
    render(); 

    //then it sets then back to Date.now() 
    then = now; 

    //No idea what this line does. still looking into it 
    requestAnimationFrame(main); 
}; 
+0

我投票作爲題外話,因爲它是要求找到一些示例源代碼 – rlemon

+0

'then'在一個層次較高的範圍,無疑宣佈的聲明,關閉了這個問題 - 最有可能 - 主關閉。表達式函數變量'main'用於(無疑)更新調用之間的時間間隔並呈現相應的幀;將'then'更新爲'now',使其爲隨後的調用相同表達式(main)的'requestAnimationFrame'做好準備,以進行新的更新和delta計算。 –

回答

0

我將嘗試解釋我從教程中的代碼中理解的內容。
遊戲通常以固定的幀率運行,如每秒60幀(FPS)。
在教程中,情況並非如此。 而不是固定的幀率和在update函數中移動固定距離的字符,您有一個delta變量用於計算距離。

hero.y -= hero.speed * modifier; // modifier is (delta/1000) 

像其他的答案說,then在開始設置,在主函數的外部範圍。

// Let's play this game! 
var then = Date.now(); 
reset(); 
main(); 

我會補充說教程有點舊(2011),有些細節可以改進。例如,您可以使用performance.now()而不是如lighthouse所報告的Date.now()。

0

閱讀開始遊戲人數10:

// Let's play this game! 
var then = Date.now(); 
reset(); 
main(); 

下面的描述還:

「幾乎在那裏,這是最後一個代碼片段!首先,我們設置我們的時間戳(然後是變量),然後我們調用重置來開始一個新的遊戲/關卡。「

+0

請在提問前仔細閱讀 – yass

+0

乾杯!完全錯過了它在調用函數之前聲明的內容。 – Melvin

0

沒有讀得不夠好。找到了聲明。謝謝!