12.5 Let’s Animate!
That is all pretty cool, but you know what’s even cooler than a shiny donut
casting a shadow? A shiny donut casting a shadow and spinning!
Replace the renderer.render() at the bottom of our code:
varclock =newTHREE.Clock();
functionanimate() {
requestAnimationFrame(animate);
vartime = clock.getElapsedTime();
donut.rotation.set(time, 2*time, 0);
renderer.render(scene, camera);
}
animate();
We’ve seen a lot of that code before, but now is a good time to explain it. Our
3D library provides the clock. It is extremely useful for finding out how much
time has gone by since the animation began. This “elapsed time” is useful for
animating all sort of things.
In this code, we use it to set the rotation of the donut around the x-axis and
the y-axis. As the seconds tick by, the donut’s rotation will go from zero to
0.5, to 1, and eventually to 2 × pi (a full rotation). And then it keeps on
rotating another spin to 4 × pi, then 6 × pi, and on and on forever (or until
the computer can no longer count that high). We spin around the y-axis twice
as fast as the x-axis to give it a crazy, wobbly motion.
It’s a little weird using the number of seconds for the amount of rotation.
Then again, they are both just numbers. The clock.getElapsedTime() call gives us
the number of seconds and we use the same number to be the number of
radians the donut has turned.
report erratum • discuss
Let’s Animate! • 115
Prepared exclusively for Michael Powell