我試圖實現使用delta時間的gameloop。我從this article得到了以下代碼,但是我覺得它並沒有很好地解釋這種類型的gameloop。我已經研究過requestAnimationFrame,並且沒有任何的補充似乎是有用的。有人可以簡單地分解這個循環的工作原理嗎?Javascript - 使用delta時間的gameloop
function timestamp() {
return window.performance && window.performance.now ? window.performance.now() : new Date().getTime();
},
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);
upvote ...還提到當前版本的requestAnimationFrame會自動給動畫函數提供一個時間戳。您可以使用該時間戳來計算自上次進入動畫循環以來經過了多長時間。重要的是:經過的時間可以用來移動你的角色基於經過的時間,而不是(可能是不規則的)動畫循環計數 – markE