![](/img/trans.png)
[英]requestAnimationFrame when using mouse cordinates to make animation
[英]When using requestAnimationFrame, how to make part of animation update faster
我正在使用requestAnimationFrame做一個游戲(游戲像蛇),游戲的幀更新速度最初是每秒更新一次
它需要將這條蛇的“requestAnimationFrame”從每次一秒更新到每次0.5秒。 由於許多蛇的設計,當蛇接觸任何物品時,它會獲得 10 秒的加速情況。
我的問題是如何維護主要的“requestAnimationFrame”(每秒更新一次),還有另一個“requestAnimationFrame”(每0.5秒更新一次)?
主請求動畫幀代碼
let speed = 1;
let lastRenderTime = 0;
const doAnimation = function (currentTime) {
window.requestAnimationFrame(doAnimation);
const secondRender = (currentTime - lastRenderTime) / 1000; // secondRender is used to control the update per second
if (secondRender < 1 / speed) {
return;
}
lastRenderTime = currentTime
}
window.requestAnimationFrame(doAnimation);
requestAnimationFrame
射速通常在 60Hz 左右。 即每秒 60 次調用,最大理論精度約為 16 毫秒(0.016 秒)。
這意味着在您的循環中,您可以使事物以高於此的任何速率進行更新。 但是為什么要截斷精度呢?
requestAnimationFrame
的全部意義在於准確了解重繪何時發生,並在正確的時間傳遞有關您的 animation 的信息。 舉個例子:如果你的蛇必須每秒移動 1000 像素,你為什么要每秒通知瀏覽器更新? 理想情況下,您應該在每一幀上更新您的視圖。 所以在這個例子中,每 16 毫秒有 16 像素的變化。
請參閱以下代碼段,並注意在任何地方都沒有條件。 但只是不斷更新。
顯然最終的實現將取決於您的用例,但這只是工作原理。
const boxA = document.getElementById('boxA'); // DEMO const boxB = document.getElementById('boxB'); // DEMO let xA = 0; // DEMO let xB = 0; // DEMO const speedA = 80; // [px/s] const speedB = 160; // [px/s] let then = 0; const animate = function (now) { window.requestAnimationFrame(animate); const delta = (now - then) / 1000; // A const a = speedA * delta; boxA.style.transform = `translateX(${xA += a}px)`; // DEMO // B const b = speedB * delta; boxB.style.transform = `translateX(${xB += b}px)`; // DEMO then = now } window.requestAnimationFrame(animate);
.container { display: flex; flex-direction: column; } #boxA, #boxB { display: inline-block; height: 50px; width: 50px; transform: translateX(0); } #boxA { background-color: #ff0000; } #boxB { background-color: #0000ff; }
<div class='container'> <span id='boxA'></span> <span id='boxB'></span> </div>
let then, then2; (function loop(delta) { then = then || delta; then2 = then2 || delta; let time = delta - then; let time2 = delta - then2; if (time > 1000) { then = delta; // in here every second } if (time2 > 500) { then2 = delta; // in here every 0.5 seconds } document.body.innerHTML = time.toFixed(2) + '<br>' + time2.toFixed(2); requestAnimationFrame(loop); })();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.