Book Image

Three.js Cookbook

By : Jos Dirksen
Book Image

Three.js Cookbook

By: Jos Dirksen

Overview of this book

Table of Contents (15 chapters)
Three.js Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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:

        function setupKeyControls() {
          var cube = scene.getObjectByName('cube');
          document.onkeydown = function(e) {
            switch (e.keyCode) {
              case 37:
              cube.rotation.x += 0.1;
              break;
              case 38:
              cube.rotation.z -= 0.1;
              break;
              case 39:
              cube.rotation.x -= 0.1;
              break;
              case 40:
              cube.rotation.z += 0.1;
              break;
            }
          };
        }
  2. In this function, we use the keyCode property from the passed event e in order to determine what to do. In this example, if a user presses the left arrow key that corresponds to key code 37, we change the rotation.x property of the Three.js object in our scene. We apply the same principle to the up arrow key(38), the right arrow (39), and the down arrow (40).

How it works...

Using event handlers is a standard HTML JavaScript mechanism, they are a part of the DOM API. This API allows you to register functions for all kinds of different events. Whenever that specific event occurs, the provided function is called. In this recipe, we chose to use the KeyDown event. This event is triggered when the user presses a key. There is also a KeyUp event available that is triggered when the user releases a key, which one to use depends on your use case. Note that there is also a KeyPress event available. This event, though, is meant to be used with characters and doesn't register any noncharacter key press.

There's more...

In this recipe, we only showed the key code values for the arrows. There is, of course, a separate key code for each key on your keyboard. A good explanation of how the various keys are mapped (especially, the special ones such as the function keys) can be found at http://unixpapa.com/js/key.html. If you want to know the key value of a specific key, and you don't feel like looking up the value in a list, you can also use just the following simple handler to output the key codes to the JavaScript console:

    function setupKeyLogger() {
      document.onkeydown = function(e) {
        console.log(e);
      }
    }

This small handler logs the complete event. In the output to the console, you can then see the key code that is used, as shown in the following screenshot:

As you can see, you also see a lot of other interesting information. For instance, you can see whether the shift or Alt keys were also pressed at the same time of the event.

See also