This code runs 60 times a second but I want to be able to increase the FPS
function animate4() {
ctx.clearRect(0, 0, cw, ch)
gamearray.forEach((layer) =>{
layer.update()
})
if (paause === true) {
return
}else {
requestAnimationFrame(animate4)
}
}
animate4()
What I’m trying to do is let the users choose diff FPS to run the game at without the game speeding up.
I tried to search for it in here but the answers are not very clear for me and the answers were for a diff problem that was also related to requestAnimationFrame timing.
2
Answers
According to MDN documentation, the rate at which requestAnimationFrame fires generally matches the refresh rate of the monitor: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
You can prevent the game from speeding up in case of a faster refresh rate by providing a timestamp to animate4, and modifying your update function so that it is dependent on the time elapsed since the last frame:
This way, even if the game is running at above 60fps, the update function will change the screen less, so that the game still looks smooth.
To render at below 60fps, check out Controlling fps with requestAnimationFrame?
This answer describes how to reduce the FPS below what you get by default.
As for increasing the FPS: The browser determines the maximum FPS based on your hardware. If your monitor only has a 60Hz refresh rate, you probably won’t get more than 60 animation frame callbacks per second. If your machine has limited processing power or is in a "battery saver" mode, the callback rate will also be reduced. The HTML standard doesn’t prescribe a specific callback rate:
(event-loop-processing-model)
Right now, Chrome and Firefox both give you 240 callbacks per second if your hardware supports it. There’s an ongoing discussion on the webkit bugtracker about higher refresh rates. You can use testufo.com to test the browser FPS for your hardware.
Zoravur Singh’s answer describes how to control the game speed using the timestamp passed to
requestAnimationFrame()
.