Game loop animation
Our general approach to animation goes like this: Render from state. Change state 60 times per second. Animation!
We're going to use two different ways of changing state so often. The first follows a game loop principle, which gives you more control, but is more tedious. The second is using D3 transitions, which is quicker to build, but gives you less control.
We're going to start with an example or two in CodeSandbox, then build something more involved.
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. 🤔
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 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's a sandbox I prepared for you earlier:
Build a bouncy ball :)
Remember that gravity is an acceleration pointing down. It impacts the speed of your ball, not its position directly.
- Render the ball
- Use an effect to start a timer with
d3.timer(it's like setInterval but better) - Ensure you clean up with
timer.stop() - Move the ball on each timer iteration (also known as a tick)
- Adjust the ball's speed to simulate gravity
How do you get the bounce effect at max_h? Look at the direction vY points.
Here's my solution
