Adding keyboard controls

If you want to create games or more advanced 3D scenes, you often need a way to control elements in your scene using keyboard controls. For instance, you might make a platform game where the user uses the arrows on the keyboard to move through your game. Three.js in itself doesn't provide a specific functionality to handle keyboard events, since it is very easy to connect the standard HTML JavaScript event handling to Three.js.

Getting ready

For this recipe, we included an example where you can rotate a cube around its x and z axes using the arrows on your keyboard. If you first open an example 01.10-keyboard-controls.html in your browser, you'll see a simple cube:

With the up, down, left, and right arrows on your keyboard, ...

Get Three.js Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.