Learning Three.js: Part 5: Controls

Requirements:

In Part 1, I covered some general terms and techniques used in Three.js, a three-dimensional rendering JavaScript library. Part 2 reviewed some of the geometry and material options in creating meshes. Part 3 demonstrated how to load and use textures (images) for those same meshes as a continuation of building from the first example code. Part 4 showed examples using the light source objects PointLight, SpotLight, and AmbientLight. In this fifth, final part, I cover different controls for Three.js.

Officially, there are no controls for Three.js. Inside of the library itself, there are no control schemes nor ways of moving objects via user input. However, inside the collection of examples are two different main ways to approach this problem: OrbitControls and PointerLockControls (FirstPersonControls).

OrbitControls

OrbitControls interprets mouse movement as rotational force. Through clicking and moving the mouse, all objects will rotate along the y-axis in that direction.

Using OrbitControls requires a simple, one-line change to the code from Part 4. We only need add a line for the controls and the code will handle input sources itself. However, while only the one line is needed in the example code, an entire, extra file should also be included in the webpage for full compatibility.

lojh7mt5bw

PointerLockControls (First Person Controls)

In order to react according to full mouse and keyboard input, the Pointer Lock functionality part of browsers can be set up, called, and used. However, this requires, like with OrbitControls, much more code and an additional file to work with Three.js.

Note: While there is an existing PointerLockControls object and file, I have written my own that combines different inputs into a single file.

Building from the Part 4 code, and wanting to differentiate between the box and a ‘floor,’ the code now loads an additional texture, sets up a hemisphere light, plane geometry, and re-uses the same example code.

While OrbitControls handled input for us, FirstPersonControls handles input but also needs an additional function, playerControls(), to update the velocity and “move” the camera as a result.

rsfrndap33

Part 5 FirstPersonControls Code (Full Example)