-
Notifications
You must be signed in to change notification settings - Fork 15
Open
Labels
enhancementNew feature or requestNew feature or request
Description
requestAnimationFrame() (rAF) is a more performant and precise alternative to setInterval() run animation loops in JavaScript that is well supported across browsers. This talk has more details on why that is the case.
Switching the code to rAF should be straightforward:
- In the
rendermember of the game data, declare a variable to track the last game update and another for the target delay between frames (1000 ms divided by the target FPS).
render: {
lastUpdate: null,
frameInterval: 1000 / 30, // 30 FPS
},Then, change the main loop to use rAF. Whenever rAF is called before an update is due, skip the rendering code.
/**
* Main loop
*/
function main() {
const render = (timestamp) => {
// If this is the first frame, or frameInterval has passed, render the frame.
if (!data.render.lastUpdate ||
(timestamp - data.render.lastUpdate > data.render.frameInterval)) {
clearScreen();
rayCasting();
data.render.lastUpdate = timestamp;
}
// Schedule the next frame to be rendered.
requestAnimationFrame(render);
};
requestAnimationFrame(render);
}Let me know if this makes sense to you, and I'll be happy to write a pull request updating the code and tutorials.
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request