Learning Three.js Part 3 – Animation Basics

In the previous post we looked at setting up a basic scene, adding a camera, lights, fog and our red cube. In this post we are going to add a plane to our scene and setup a basic animation loop.

Before we get started, let’s have a look at what we’ll be creating

The biggest change from the previous post is the inclusion of an animation loop. We’ll be using JavaScripts requestAnimationFrame() method which tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. To do this we will move our renderer.render(scene, camera); inside a function like so:

render = function(){				
	renderer.render(scene, camera);
	requestAnimationFrame(render);
}

You’ll see that inside our render function we recursively call the render function using requestAnimationFrame(). If you’re familiar with Unity you can think of this like Unity’s Update() function. This function is going to repeatedly be called, and every time it’s called it will render the scene. So to animate our cubes rotation we can simply add:

render = function(){	
	cube.rotation.y = cube.rotation.y + 0.01;			
	renderer.render(scene, camera);
	requestAnimationFrame(render);
}

This will increase the cubes rotation property on the y axis by 0.01 radians every time the render() function is called. Our scene is starting to look pretty cool! As always, the source code is available on github. See you soon for the next part of our series where we look at dynamically creating objects in the scene at runtime