Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Three.js Cookbook
  • Table Of Contents Toc
Three.js Cookbook

Three.js Cookbook

By : Jos Dirksen
4 (8)
close
close
Three.js Cookbook

Three.js Cookbook

4 (8)
By: Jos Dirksen

Overview of this book

This book is ideal for anyone who already knows JavaScript and would like to get a broad understanding of Three.js quickly, or for those of you who have a basic grasp of using Three.js but want to really make an impact with your 3D visualizations by learning its advanced features. To apply the recipes in this book you don’t need to know anything about WebGL; all you need is some general knowledge about JavaScript and HTML.
Table of Contents (9 chapters)
close
close
8
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

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Three.js Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon