[英]How should I organize my update/draw logic when using requestAnimationFrame?
我的 HTML5 游戲的 JavaScript 代碼結構如下:
// <body onload="load()">
function load() {} // Load all images then call init()
function init() {} // Get all images ready for the game logic then call animate()
function animate() {} // Use requestAnimationFrame(), update() and drawing()
function update() {} // Update the game logic
function drawing() {} // Render the images on canvas
問題在於animate()
。 我沒有在 web 周圍找到任何一致的來源,說明如何在其中組織requestAnimationFrame()
、 update()
和drawing()
。
我試圖自己詳細說明它,但游戲確實以任何方法運行,例如將animate()
、 update()
或drawing()
作為參數傳遞給requestAnimationFrame()
,或者在開始時使用requestAnimationFrame()
或function 的末尾,或以任何順序具有這些功能中的任何一個,或一個 function 在另一個內部,等等。
然而,這並不意味着一切都好。 其中一些安排會導致我稍后才發現的問題,例如在不同的計算機或以不同的幀速率進行測試時。 然后我必須將 go 回到代碼中嘗試另一種方法。
那么,我應該如何組織呢? 如果您能給我一個合適的算法,我將不勝感激,如果您有任何關於它的良好教學資源,我將不勝感激。
使用requestAnimationFrame
調用animate
。 animate
調用update
然后draw
。 基本上就是這樣。 由於您不能精確控制時間間隔,因此為了更好地控制時間,傳遞最后一次調用animate
是有意義的。 也許事件之后的增量時間更有意義。 然后你可以使用增量時間來計算給定速度的距離等等。
這是“官方”游戲循環如下所示:
var now,
dt = 0,
last = timestamp(),
step = 1/60;
function frame() {
now = timestamp();
dt = dt + Math.min(1, (now - last) / 1000);
while(dt > step) {
dt = dt - step;
update(step);
}
render(dt);
last = now;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
網上有很多資源。 對於初學者來說,這是一個不錯的https://www.sitepoint.com/quick-tip-game-loop-in-javascript/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.