...

/

Using a game loop for rich animation

Using a game loop for rich animation

I love game loops. It even sounds fun: “game loop”. Maybe it’s just that whenever I build a game loop, the thing I’m building is fun to play with. :thinking_face:

A game loop is an infinite loop where each iteration renders the next frame of your game or animation. You do your best to complete each iteration in 16 milliseconds, and your user gets smooth animation.

As you can imagine, our challenge is to cram all the physics and rendering into those 16 milliseconds. The more elements you’re rendering, the harder it gets.

A bouncing ball

Let’s get our feet wet with my favorite childhood example: a bouncing ball.

I must have built dozens of them back in my Turbo Pascal days using BGI. Yes, those Turbo Pascal and BGI are from the 80’s. No, I’m not that old. I just started young and with old equipment. Coding for DOS is easier when you’re a kid than coding for Windows 95.

Here is a screenshot of our bouncing ball:

widget

Exciting, isn’t it? Took me five tries to catch it. Future examples will look better as screenshots, I promise.

I suggest you follow along the code widgets. Here’s one I prepared for you earlier:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Step 1: stub it out

...
Access this course and 1400+ top-rated courses and projects.