Skip to content

Follow Cam

Description

In this custom implementation of a follow cam, a.k.a., third person camera, I have a camera pivot, which I attach to an object that I want to follow. The pivot can be rotated by moving the mouse left, right, up and down.

The pivot has a yaw and pitch THREE.Object3D, and the camera added to the bottom of the hierarchy offset some distance. The distance can be changed using the scroll wheel. While the yaw and pitch are controlled by the mouse movement.

The pivot follows the main character of the scene. The pivot lerps to the position of the character collider.

<>

./src/client/client.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import Stats from 'three/examples/jsm/libs/stats.module'
import * as CANNON from 'cannon-es'
import CannonDebugRenderer from './utils/cannonDebugRenderer'

const scene = new THREE.Scene()

const light1 = new THREE.SpotLight(0xffffff, 100)
light1.position.set(2.5, 5, 2.5)
light1.angle = Math.PI / 8
light1.penumbra = 0.5
light1.castShadow = true
light1.shadow.mapSize.width = 1024
light1.shadow.mapSize.height = 1024
light1.shadow.camera.near = 0.5
light1.shadow.camera.far = 20
scene.add(light1)

const light2 = new THREE.SpotLight(0xffffff, 100)
light2.position.set(-2.5, 5, 2.5)
light2.angle = Math.PI / 8
light2.penumbra = 0.5
light2.castShadow = true
light2.shadow.mapSize.width = 1024
light2.shadow.mapSize.height = 1024
light2.shadow.camera.near = 0.5
light2.shadow.camera.far = 20
scene.add(light2)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.01,
    100
)
camera.position.set(0, 0, 2)

const pivot = new THREE.Object3D()
pivot.position.set(0, 1, 10)

const yaw = new THREE.Object3D()
const pitch = new THREE.Object3D()

scene.add(pivot)
pivot.add(yaw)
yaw.add(pitch)
pitch.add(camera)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement)

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)

const groundMaterial = new CANNON.Material('groundMaterial')
const slipperyMaterial = new CANNON.Material('slipperyMaterial')
const slippery_ground_cm = new CANNON.ContactMaterial(
    groundMaterial,
    slipperyMaterial,
    {
        friction: 0,
        restitution: 0.3,
        contactEquationStiffness: 1e8,
        contactEquationRelaxation: 3,
    }
)
world.addContactMaterial(slippery_ground_cm)

// Character Collider
const characterCollider = new THREE.Object3D()
characterCollider.position.y = 3
scene.add(characterCollider)
const colliderShape = new CANNON.Sphere(0.5)
const colliderBody = new CANNON.Body({ mass: 1, material: slipperyMaterial })
colliderBody.addShape(colliderShape, new CANNON.Vec3(0, 0.5, 0))
colliderBody.addShape(colliderShape, new CANNON.Vec3(0, -0.5, 0))
colliderBody.position.set(
    characterCollider.position.x,
    characterCollider.position.y,
    characterCollider.position.z
)
colliderBody.linearDamping = 0.95
colliderBody.angularFactor.set(0, 1, 0) // prevents rotation X,Z axis
world.addBody(colliderBody)

let mixer: THREE.AnimationMixer
let modelReady = false
let modelMesh: THREE.Object3D
const animationActions: THREE.AnimationAction[] = []
let activeAction: THREE.AnimationAction
let lastAction: THREE.AnimationAction

const gltfLoader = new GLTFLoader()
gltfLoader.load(
    'models/eve.glb',
    (gltf) => {
        gltf.scene.traverse(function (child) {
            if ((child as THREE.Mesh).isMesh) {
                let m = child
                m.receiveShadow = true
                m.castShadow = true
                m.frustumCulled = false
                ;(m as THREE.Mesh).geometry.computeVertexNormals()
                if ((child as THREE.Mesh).material) {
                    const mat = (child as THREE.Mesh).material
                    ;(mat as THREE.Material).transparent = false
                    ;(mat as THREE.Material).side = THREE.FrontSide
                }
            }
        })
        mixer = new THREE.AnimationMixer(gltf.scene)
        let animationAction = mixer.clipAction(gltf.animations[0])
        animationActions.push(animationAction)
        activeAction = animationActions[0]
        scene.add(gltf.scene)
        modelMesh = gltf.scene
        light1.target = modelMesh
        light2.target = modelMesh

        //add an animation from another file
        gltfLoader.load(
            'models/eve@walking.glb',
            (gltf) => {
                console.log('loaded Eve walking')
                let animationAction = mixer.clipAction(gltf.animations[0])
                animationActions.push(animationAction)

                gltfLoader.load(
                    'models/eve@jump.glb',
                    (gltf) => {
                        console.log('loaded Eve jump')
                        gltf.animations[0].tracks.shift() //delete the specific track that moves the object up/down while jumping
                        let animationAction = mixer.clipAction(
                            gltf.animations[0]
                        )
                        animationActions.push(animationAction)
                        //progressBar.style.display = 'none'
                        modelReady = true

                        setAction(animationActions[1], true)
                    },
                    (xhr) => {
                        if (xhr.lengthComputable) {
                            //const percentComplete = (xhr.loaded / xhr.total) * 100
                            //progressBar.value = percentComplete
                            //progressBar.style.display = 'block'
                        }
                    },
                    (error) => {
                        console.log(error)
                    }
                )
            },
            (xhr) => {
                if (xhr.lengthComputable) {
                    //const percentComplete = (xhr.loaded / xhr.total) * 100
                    //progressBar.value = percentComplete
                    //progressBar.style.display = 'block'
                }
            },
            (error) => {
                console.log(error)
            }
        )
    },
    (xhr) => {
        if (xhr.lengthComputable) {
            //const percentComplete = (xhr.loaded / xhr.total) * 100
            //progressBar.value = percentComplete
            //progressBar.style.display = 'block'
        }
    },
    (error) => {
        console.log(error)
    }
)

const setAction = (toAction: THREE.AnimationAction, loop: Boolean) => {
    if (toAction != activeAction) {
        lastAction = activeAction
        activeAction = toAction
        lastAction.fadeOut(0.1)
        activeAction.reset()
        activeAction.fadeIn(0.1)
        activeAction.play()
        if (!loop) {
            activeAction.clampWhenFinished = true
            activeAction.loop = THREE.LoopOnce
        }
    }
}

let moveForward = false
let moveBackward = false
let moveLeft = false
let moveRight = false
let canJump = true
const contactNormal = new CANNON.Vec3()
const upAxis = new CANNON.Vec3(0, 1, 0)
colliderBody.addEventListener('collide', function (e: any) {
    const contact = e.contact
    if (contact.bi.id == colliderBody.id) {
        contact.ni.negate(contactNormal)
    } else {
        contactNormal.copy(contact.ni)
    }
    if (contactNormal.dot(upAxis) > 0.5) {
        if (!canJump) {
            setAction(animationActions[1], true)
        }
        canJump = true
    }
})

const planeGeometry = new THREE.PlaneGeometry(100, 100)
const texture = new THREE.TextureLoader().load('img/grid.png')
const plane = new THREE.Mesh(
    planeGeometry,
    new THREE.MeshPhongMaterial({ map: texture })
)
plane.rotateX(-Math.PI / 2)
plane.receiveShadow = true
scene.add(plane)
const planeShape = new CANNON.Plane()
const planeBody = new CANNON.Body({ mass: 0, material: groundMaterial })
planeBody.addShape(planeShape)
planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
world.addBody(planeBody)

const boxes: CANNON.Body[] = []
const boxMeshes: THREE.Mesh[] = []
for (let i = 0; i < 25; i++) {
    const halfExtents = new CANNON.Vec3(
        Math.random() * 2,
        Math.random() * 2,
        Math.random() * 2
    )
    const boxShape = new CANNON.Box(halfExtents)
    const boxGeometry = new THREE.BoxGeometry(
        halfExtents.x * 2,
        halfExtents.y * 2,
        halfExtents.z * 2
    )
    const x = (Math.random() - 0.5) * 20
    const y = 2 + i * 2
    const z = (Math.random() - 0.5) * 20
    const boxBody = new CANNON.Body({ mass: 1, material: groundMaterial })
    boxBody.addShape(boxShape)
    const boxMesh = new THREE.Mesh(
        boxGeometry,
        new THREE.MeshStandardMaterial()
    )
    world.addBody(boxBody)
    scene.add(boxMesh)
    boxBody.position.set(x, y, z)
    boxMesh.castShadow = true
    boxMesh.receiveShadow = true
    boxes.push(boxBody)
    boxMeshes.push(boxMesh)
}

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

function onDocumentMouseMove(e: MouseEvent) {
    e.preventDefault()
    yaw.rotation.y -= e.movementX * 0.002
    const v = pitch.rotation.x - e.movementY * 0.002
    if (v > -1 && v < 0.1) {
        pitch.rotation.x = v
    }
}

function onDocumentMouseWheel(e: WheelEvent) {
    e.preventDefault()
    const v = camera.position.z + e.deltaY * 0.005
    if (v >= 0.5 && v <= 5) {
        camera.position.z = v
    }
}

const menuPanel = document.getElementById('menuPanel') as HTMLDivElement
const startButton = document.getElementById('startButton') as HTMLInputElement
startButton.addEventListener(
    'click',
    () => {
        renderer.domElement.requestPointerLock()
    },
    false
)

let pointerLocked = false
document.addEventListener('pointerlockchange', () => {
    if (document.pointerLockElement === renderer.domElement) {
        pointerLocked = true

        startButton.style.display = 'none'
        menuPanel.style.display = 'none'

        document.addEventListener('keydown', onDocumentKey, false)
        document.addEventListener('keyup', onDocumentKey, false)

        renderer.domElement.addEventListener(
            'mousemove',
            onDocumentMouseMove,
            false
        )
        renderer.domElement.addEventListener(
            'wheel',
            onDocumentMouseWheel,
            false
        )
    } else {
        menuPanel.style.display = 'block'

        document.removeEventListener('keydown', onDocumentKey, false)
        document.removeEventListener('keyup', onDocumentKey, false)

        renderer.domElement.removeEventListener(
            'mousemove',
            onDocumentMouseMove,
            false
        )
        renderer.domElement.removeEventListener(
            'wheel',
            onDocumentMouseWheel,
            false
        )

        setTimeout(() => {
            startButton.style.display = 'block'
        }, 1000)
    }
})

const keyMap: { [id: string]: boolean } = {}
const onDocumentKey = (e: KeyboardEvent) => {
    keyMap[e.code] = e.type === 'keydown'

    if (pointerLocked) {
        moveForward = keyMap['KeyW']
        moveBackward = keyMap['KeyS']
        moveLeft = keyMap['KeyA']
        moveRight = keyMap['KeyD']

        if (keyMap['Space']) {
            if (canJump === true) {
                colliderBody.velocity.y = 10
                setAction(animationActions[2], false)
            }
            canJump = false
        }
    }
}

const inputVelocity = new THREE.Vector3()
const velocity = new CANNON.Vec3()
const euler = new THREE.Euler()
const quat = new THREE.Quaternion()
const v = new THREE.Vector3()
const targetQuaternion = new THREE.Quaternion()
let distance = 0

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

const clock = new THREE.Clock()
let delta = 0

//const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

function animate() {
    requestAnimationFrame(animate)

    if (modelReady) {
        if (canJump) {
            //walking
            mixer.update(delta * distance * 5)
        } else {
            //were in the air
            mixer.update(delta)
        }
        const p = characterCollider.position
        p.y -= 1
        modelMesh.position.y = characterCollider.position.y
        distance = modelMesh.position.distanceTo(p)

        const rotationMatrix = new THREE.Matrix4()
        rotationMatrix.lookAt(p, modelMesh.position, modelMesh.up)
        targetQuaternion.setFromRotationMatrix(rotationMatrix)

        if (!modelMesh.quaternion.equals(targetQuaternion)) {
            modelMesh.quaternion.rotateTowards(targetQuaternion, delta * 10)
        }

        if (canJump) {
            inputVelocity.set(0, 0, 0)

            if (moveForward) {
                inputVelocity.z = -10 * delta
            }
            if (moveBackward) {
                inputVelocity.z = 10 * delta
            }

            if (moveLeft) {
                inputVelocity.x = -10 * delta
            }
            if (moveRight) {
                inputVelocity.x = 10 * delta
            }

            // apply camera rotation to inputVelocity
            euler.y = yaw.rotation.y
            euler.order = 'XYZ'
            quat.setFromEuler(euler)
            inputVelocity.applyQuaternion(quat)
        }

        modelMesh.position.lerp(characterCollider.position, 0.1)
    }
    velocity.set(inputVelocity.x, inputVelocity.y, inputVelocity.z)
    colliderBody.applyImpulse(velocity)

    delta = Math.min(clock.getDelta(), 0.1)
    world.step(delta)

    //cannonDebugRenderer.update()

    characterCollider.position.set(
        colliderBody.position.x,
        colliderBody.position.y,
        colliderBody.position.z
    )
    boxes.forEach((b, i) => {
        boxMeshes[i].position.set(b.position.x, b.position.y, b.position.z)
        boxMeshes[i].quaternion.set(
            b.quaternion.x,
            b.quaternion.y,
            b.quaternion.z,
            b.quaternion.w
        )
    })

    characterCollider.getWorldPosition(v)
    pivot.position.lerp(v, 0.1)

    render()

    stats.update()
}

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

animate()

Comments