Game loop

See also: Game states

optimisation

A game loop should be able to:

  • perform async?
  • have separate rendering loop and logic loop should be host frame rate independent – delta time – but never need to exceed the display refresh rate…
  • Pause rendering loop and logic loop

SOURCE: https://gameprogrammingpatterns.com/game-loop.html

Javascript – best practices for performant gameloops

Performance is based upon how many things a game has to do each iteration of the loop. If you can defer a task, good. If you can store and reuse something, good. Consider if things could go in an alternative loop at a different refresh rate

  • logic loop step (alternate fps)
  • render loop step (60fps)
    • clear screen
    • draw screen
    • end

a method called “step” that calls ‘requestAnimationFrame()
By having the ‘step’ called in a loop in the request animation, there is a chance for other processes to run, so it won’t crash via an infinite loop. Good!

startGameLoop() {
    const step = () => {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        requestAnimationFrame(() => {
            step();
         })
    }
    step();
}

OPTIMIZATION
We currently now have a few loops running at the same time, so if we are having hundreds of objects at once, this could be an issue…

Work with the language and platform you are targeting – e.g. the javascript event loop is built into the browser… and the fact that it is a single threaded language…

Make the data do its thing, then render

– such as the logic…

Start by clearing the screen

It is usual to clear the screen at the start of the game loop, then redraw the stuff.

A basic javascript game loop

window.requestAnimationFrame(gameLoop);

function gameLoop() {
    draw();
    window.requestAnimationFrame(gameLoop);
}

Also, having a timestamp when the loop runs – then can keep the game to run evenly…

delta time

time diff between now and how long ago since the last frame ran…

rendering fps vs game loop fps

Separating the rendering and game loop means they can run at different speeds – e.g. game loop can quite easily run at ½ or ¼ the rendering frame rate of 60 fps…

see: github.com/kittykatattack/smoothie

References

general

https://gameprogrammingpatterns.com/game-loop.html

javascript

https://jsforgames.com/game-loop

https://www.isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing

https://medium.com/@kristenrogers.kr75/how-to-make-a-game-loop-in-javascript-e7d2838bbe33

http://creativejs.com/resources/requestanimationframe/

https://stackoverflow.com/questions/1955687/best-way-for-simple-game-loop-in-javascript

https://www.sitepoint.com/quick-tip-game-loop-in-javascript