How to use PointerLockControls
This tutorial will cover how to use the PointerLockControls
module for three.js
.
Tutorial difficulty: Fairly easy
Before starting..
You'll need:
- A basic Three.js app (render loop & init, some objects?)
- Basic knowledge of JavaScript
- Patience: Some
Setup
To add the module, use the following code:
import {PointerLockControls} from 'https://threejs.org/examples/jsm/PointerLockControls.js'
To add the controls, use:
const controls = new PointerLockControls(camera,renderer.domElement)
Insert the code above into your init
function, or where you are defining your camera
,scene
,renderer
,etc
When you run your app now, you will probably get an error and nothing will happen. This is because we are not done yet.
To lock your pointer (for looking around), you need to callcontrols.lock()
. For security reasons, you can't do this automatically, you need to do this from user interaction (e.g mousedown event).
Now, to make the controls work, you need to set up keydown
and keyup
functions.
You need to create an array called keys
. When a key is pressed, keys['key'] will become true
. When the key is lifted (no longer pressed), keys['key'] changes to false
.
We'll be attaching keydown
and keyup
to renderer.domElement
(the canvas).
let keys = [];//Define array
renderer.domElement.addEventListener('keydown',keydown);
renderer.domElement.addEventListener('keyup',keyup);
//Attach listeners to functions
function keydown(e){
keys[e.key] = true;
}
function keyup(e){
keys[e.key] = false;
}
Now, we can use the keys
array in our render loop, to make movement work.
At this point, you'll need to set the keys that you want to use to move forward, backward, left, and right.
Usually, I use W, A, S, and D, or arrow keys.
Tip: Arrow keys are called 'ArrowDown/Left/Up' on events.
In your render loop, BEFORE renderer.render(...)
(after will cause weird effects), insert the following code:
Before you start..
Set .1
to the speed you want to move (or just .1)
Set W/A/S/D
to the keys you wish to use.
if(keys['w']){
controls.moveForward(.1);
}
if(keys['s']){
controls.moveForward(-.1);
}
if(keys['a']){
controls.moveRight(-.1);
}
if(keys['d']){
controls.moveRight(.1);
}
Run your app, and that's it!
Hope you learned something from this tutorial :)