Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Three.js Cookbook

You're reading from   Three.js Cookbook Over 80 shortcuts, solutions, and recipes that allow you to create the most stunning visualizations and 3D scenes using the Three.js library

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher Packt
ISBN-13 9781783981182
Length 300 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Jos Dirksen Jos Dirksen
Author Profile Icon Jos Dirksen
Jos Dirksen
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Getting Started 2. Geometries and Meshes FREE CHAPTER 3. Working with the Camera 4. Materials and Textures 5. Lights and Custom Shaders 6. Point Clouds and Postprocessing 7. Animation and Physics 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:

Getting ready

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:

There's more...

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image