Skip to content

PointerLockControls

Video Lecture

PointerLock Controls PointerLockControls

Description

The PointerLockControls implements the browsers inbuilt Pointer Lock API.

It provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport.

It gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view.

Furthermore, it's commonly used for first person view 3D games.

<>

Lesson Scripts

Resources

This lesson uses 2 images for the lens flare. The images are in the zip below. Extract the contents into your ./public/img/ folder.

pointerLockControls.zip

./index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Three.js TypeScript Tutorials by Sean Bradley : https://sbcode.net/threejs</title>
  </head>

  <body>
    <div id="menuPanel">
      <button id="startButton">Click to Start</button>
    </div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

./src/style.css

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
body {
  overflow: hidden;
  margin: 0px;
}

#menuPanel {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
}

#startButton {
  height: 100px;
  width: 250px;
  margin: -50px -125px;
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 28px;
  font-family: monospace;
}

./src/main.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import './style.css'
import * as THREE from 'three'
import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js'
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'
import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js'
import { Lensflare, LensflareElement } from 'three/addons/objects/Lensflare.js'
import Stats from 'three/addons/libs/stats.module.js'
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(0, 1, 2)

const light = new THREE.DirectionalLight(0xebfeff, Math.PI)
light.castShadow = true
light.shadow.camera.far = 250
light.shadow.camera.left = -50
light.shadow.camera.right = 50
light.shadow.camera.top = 50
light.shadow.camera.bottom = -50
light.shadow.blurSamples = 10
light.shadow.radius = 5
light.target = camera
scene.add(light)

const lightOffset = new THREE.Vector3(100, 30, 70)

const lightHelper = new THREE.CameraHelper(light.shadow.camera)
lightHelper.visible = false
scene.add(lightHelper)

const textureLoader = new THREE.TextureLoader()
const textureFlare0 = textureLoader.load('img/lensflare0.png')
const textureFlare3 = textureLoader.load('img/lensflare3.png')

const lensflare = new Lensflare()
lensflare.addElement(new LensflareElement(textureFlare0, 1000, 0))
lensflare.addElement(new LensflareElement(textureFlare3, 500, 0.2))
lensflare.addElement(new LensflareElement(textureFlare3, 250, 0.8))
lensflare.addElement(new LensflareElement(textureFlare3, 125, 0.6))
lensflare.addElement(new LensflareElement(textureFlare3, 62.5, 0.4))
light.add(lensflare)

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.toneMappingExposure = 0.7
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.VSMShadowMap
document.body.appendChild(renderer.domElement)

await new RGBELoader().loadAsync('img/venice_sunset_1k.hdr').then((texture) => {
  texture.mapping = THREE.EquirectangularReflectionMapping
  scene.environment = texture
  scene.environmentIntensity = 0.1
  scene.background = scene.environment
  scene.backgroundIntensity = 0.25
  scene.backgroundBlurriness = 0.3
})

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
  render()
})

const menuPanel = document.getElementById('menuPanel') as HTMLDivElement

const startButton = document.getElementById('startButton') as HTMLButtonElement
startButton.addEventListener(
  'click',
  () => {
    controls.lock()
  },
  false
)

const controls = new PointerLockControls(camera, renderer.domElement)
controls.addEventListener('change', () => {
  console.log('pointerlock change')
})
controls.addEventListener('lock', () => (menuPanel.style.display = 'none'))
controls.addEventListener('unlock', () => (menuPanel.style.display = 'block'))

const planeGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1)
const material = new THREE.MeshStandardMaterial()
const plane = new THREE.Mesh(planeGeometry, material)
plane.rotateX(-Math.PI / 2)
plane.receiveShadow = true
scene.add(plane)

let geometries: THREE.BufferGeometry[] = []
for (let i = 0; i < 1000; i++) {
  const g = new THREE.BoxGeometry(Math.random() * 4 + 1, Math.random() * 29 + 1, Math.random() * 4 + 1)
  g.computeBoundingBox()
  g.translate(Math.random() * 500 - 250, ((g as any).boundingBox.max.y - (g as any).boundingBox.min.y) / 2, Math.random() * 500 - 250)
  geometries.push(g)
}

// merge geometries
const mergedGeometries = BufferGeometryUtils.mergeGeometries(geometries)

const cubeMaterial = new THREE.MeshStandardMaterial({ roughness: 0.12, metalness: 0.9 })
const buildings = new THREE.Mesh(mergedGeometries, cubeMaterial)
buildings.castShadow = true
buildings.receiveShadow = true
scene.add(buildings)

const keyMap: { [key: string]: boolean } = {}
const onDocumentKey = (e: KeyboardEvent) => {
  keyMap[e.code] = e.type === 'keydown'
}
document.addEventListener('keydown', onDocumentKey, false)
document.addEventListener('keyup', onDocumentKey, false)

const stats = new Stats()
document.body.appendChild(stats.dom)

const gui = new GUI({ width: 400 }).close()

const rendererFolder = gui.addFolder('Renderer')
rendererFolder.add(renderer, 'toneMappingExposure', 0, 2, 0.01)

const backgroundFolder = gui.addFolder('Background')
backgroundFolder.add(scene, 'backgroundIntensity', 0, 2, 0.01)
backgroundFolder.add(scene, 'backgroundBlurriness', 0, 2, 0.01)

const environmentFolder = gui.addFolder('Environnment')
environmentFolder.add(scene, 'environmentIntensity', 0, 2, 0.01)

const materialFolder = gui.addFolder('cubeMaterial')
materialFolder.add(cubeMaterial, 'roughness', 0, 1.0, 0.01)
materialFolder.add(cubeMaterial, 'metalness', 0, 1.0, 0.01)

const lightFolder = gui.addFolder('Light Helper')
lightFolder.add(lightHelper, 'visible')

const clock = new THREE.Clock()
let delta

function animate() {
  requestAnimationFrame(animate)

  delta = clock.getDelta()

  //controls.update() // PointerLockControls doesn't have an update method, unlike OrbitControls.

  if (keyMap['KeyW'] || keyMap['ArrowUp']) {
    controls.moveForward(delta * 25)
  }
  if (keyMap['KeyS'] || keyMap['ArrowDown']) {
    controls.moveForward(-delta * 25)
  }
  if (keyMap['KeyA'] || keyMap['ArrowLeft']) {
    controls.moveRight(-delta * 25)
  }
  if (keyMap['KeyD'] || keyMap['ArrowRight']) {
    controls.moveRight(delta * 25)
  }

  light.position.copy(camera.position).add(lightOffset)

  render()
  //console.log( renderer.info.render.calls );

  stats.update()
}

function render() {
  renderer.render(scene, camera)
}

animate()

PointerLockControls (threejs.org)

Pointer Lock API (mozilla.org)

BufferGeometryUtils (threejs.org)

KeyboardEvent.code (mozilla.org)

Comments