Graphics Reference
In-Depth Information
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 or-
der 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.