Graphics Reference
In-Depth Information
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, you can rotate this cube.
With this file open, you are now ready to begin.
How to do it...
Adding a key support in your browser is very easy; all you have to do is assign an
event handler to document.onkeydown .
1. To do this we need to assign a function to the document.onkeydown object
This function will get called whenever a key is pressed. The following code,
wrapped in the setupKeyControls function, registers this listener:
Search WWH ::




Custom Search