Skip to content

Earings

Description

Attaching physics objects to an animated model, and making the head follow the mouse.

To make the head follow the mouse, we choose a bone to control. In this case it was mixamorigNeck.

When the mouse moves across the screen, we can convert its clientX and clientY to a lookAt point and then make the bone look at that point. See the onMouseMove function.

We can also attach meshes to bones. In this example, there are meshes added to the headBone. They are offset the headBone by some amount.

Also, several more CANNON.Spheres were added to the scene, and constraints added to them to keep them a certain distance from one another in a certain order. They then hang in place as a chain, and this simulates earings.

The code also contains several comments to read.

<>

Example Script

./dist/client/index.html

 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
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Three.js TypeScript Tutorials by Sean Bradley</title>
        <style>
            body {
                overflow: hidden;
                margin: 0px;
            }
            #spinner {
                left: 50%;
                margin-left: -4em;
                font-size: 10px;
                border: 0.8em solid rgba(0, 0, 0, 1);
                border-left: 0.8em solid rgba(58, 166, 165, 1);
                animation: spin 1.1s infinite linear;
            }
            #spinner,
            #spinner:after {
                border-radius: 50%;
                width: 8em;
                height: 8em;
                display: block;
                position: absolute;
                top: 50%;
                margin-top: -4.05em;
            }
            @keyframes spin {
                0% {
                    transform: rotate(360deg);
                }
                100% {
                    transform: rotate(0deg);
                }
            }
        </style>
    </head>

    <body>
        <div id="spinner"></div>
        <script type="module" src="bundle.js"></script>
    </body>
</html>

./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
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'
import Stats from 'three/examples/jsm/libs/stats.module'
import * as CANNON from 'cannon-es'
import CannonDebugRenderer from './utils/cannonDebugRenderer'

const v = new THREE.Vector3()
const q = new THREE.Quaternion()

let earingLeft: Earing
let earingRight: Earing
let neckBone: THREE.Bone

let skeletonCollider: SkeletonCollider
let mixer: THREE.AnimationMixer
let modelReady = false

class SkeletonCollider {
    bones: THREE.Bone[] = []
    material = new THREE.MeshBasicMaterial({
        color: 0xff0000,
        wireframe: true,
        depthTest: false,
    })
    constructor(object: THREE.Group, world: CANNON.World) {
        object.traverse((child) => {
            if ((child as THREE.Bone).isBone) {
                if (child.parent && child.parent.type === 'Bone') {
                    const body = new CANNON.Body({ mass: 0 })

                    switch (child.name) {
                        case 'mixamorigHeadTop_End':
                            body.addShape(
                                new CANNON.Sphere(0.065),
                                new CANNON.Vec3(0, 0.07, 0.01)
                            )
                            body.addShape(
                                new CANNON.Sphere(0.045),
                                new CANNON.Vec3(0, 0.03, 0.035)
                            )
                            body.addShape(
                                new CANNON.Sphere(0.02),
                                new CANNON.Vec3(0, 0, 0.068)
                            )
                            break
                        case 'mixamorigHead':
                            body.addShape(
                                new CANNON.Sphere(0.04),
                                new CANNON.Vec3(0, 0.02, 0.01)
                            )
                            break
                        case 'mixamorigLeftShoulder':
                            body.addShape(
                                new CANNON.Box(
                                    new CANNON.Vec3(0.05, 0.025, 0.01)
                                ),
                                new CANNON.Vec3(0.05, 0.12, -0.03),
                                new CANNON.Quaternion(0, -0.3, -0.3, 1)
                            )
                        case 'mixamorigRightShoulder':
                            body.addShape(
                                new CANNON.Box(
                                    new CANNON.Vec3(0.05, 0.025, 0.01)
                                ),
                                new CANNON.Vec3(-0.05, 0.13, -0.035),
                                new CANNON.Quaternion(0, 0.3, 0.3, 1)
                            )
                            break
                    }

                    if (body.shapes.length) {
                        world.addBody(body)
                        this.bones.push(child as THREE.Bone)
                        child.userData.body = body
                    }
                }
            }
        })
    }

    update() {
        this.bones.forEach((b) => {
            if (b.parent) {
                b.parent.getWorldPosition(v)
                b.userData.body.position.set(v.x, v.y, v.z)
                b.parent.getWorldQuaternion(q)
                b.userData.body.quaternion.set(q.x, q.y, q.z, q.w)
            }
        })
    }
}

class Earing {
    earing: THREE.Mesh
    link1Mesh: THREE.Mesh
    link2Mesh: THREE.Mesh
    link3Mesh: THREE.Mesh
    earLobeBody: CANNON.Body
    link1Body: CANNON.Body
    link2Body: CANNON.Body
    link3Body: CANNON.Body

    constructor(bone: THREE.Bone, world: CANNON.World, offset: THREE.Vector3) {
        const material = new THREE.MeshStandardMaterial({
            color: 0xffffff,
            roughness: 0,
            metalness: 1.0,
            flatShading: true,
        })

        this.earing = new THREE.Mesh(new THREE.SphereGeometry(0.005), material)
        this.earing.position.copy(offset)
        // offset is world coords, but bone is transformed several times due to hierarchy,
        // so using `attach` method, instead of `add` to convert offset world to local transform
        bone.attach(this.earing)

        this.link1Mesh = new THREE.Mesh(
            new THREE.SphereGeometry(0.01),
            material
        )
        scene.add(this.link1Mesh)
        this.link2Mesh = this.link1Mesh.clone()
        scene.add(this.link2Mesh)
        this.link3Mesh = this.link1Mesh.clone()
        scene.add(this.link3Mesh)

        const earLobeShape = new CANNON.Sphere(0.005)
        this.earLobeBody = new CANNON.Body({ mass: 0 })
        this.earLobeBody.addShape(earLobeShape)
        this.earLobeBody.position.x = offset.x
        this.earLobeBody.position.y = offset.y
        this.earLobeBody.position.z = offset.z
        world.addBody(this.earLobeBody)

        const link1Shape = new CANNON.Sphere(0.005)
        this.link1Body = new CANNON.Body({ mass: 1 })
        this.link1Body.addShape(link1Shape)
        this.link1Body.position.x = offset.x
        this.link1Body.position.y = offset.y - 0.015
        this.link1Body.position.z = offset.z
        world.addBody(this.link1Body)

        const link2Shape = new CANNON.Sphere(0.005)
        this.link2Body = new CANNON.Body({ mass: 1 })
        this.link2Body.addShape(link2Shape)
        this.link2Body.position.x = offset.x
        this.link2Body.position.y = offset.y - 0.04
        this.link2Body.position.z = offset.z
        world.addBody(this.link2Body)

        const link3Shape = new CANNON.Sphere(0.005)
        this.link3Body = new CANNON.Body({ mass: 1 })
        this.link3Body.addShape(link3Shape)
        this.link3Body.position.x = offset.x
        this.link3Body.position.y = offset.y - 0.06
        this.link3Body.position.z = offset.z
        world.addBody(this.link3Body)

        const distanceConstraint1 = new CANNON.DistanceConstraint(
            this.earLobeBody,
            this.link1Body,
            0.015
        )
        world.addConstraint(distanceConstraint1)

        const distanceConstraint2 = new CANNON.DistanceConstraint(
            this.link1Body,
            this.link2Body,
            0.02
        )
        world.addConstraint(distanceConstraint2)

        const distanceConstraint3 = new CANNON.DistanceConstraint(
            this.link2Body,
            this.link3Body,
            0.02
        )
        world.addConstraint(distanceConstraint3)
    }

    update() {
        this.earing.getWorldPosition(v)
        this.earLobeBody.position.set(v.x, v.y, v.z)
        this.earing.getWorldQuaternion(q)
        this.earLobeBody.quaternion.set(q.x, q.y, q.z, q.w)

        this.link1Mesh.position.set(
            this.link1Body.position.x,
            this.link1Body.position.y,
            this.link1Body.position.z
        )
        this.link1Mesh.quaternion.set(
            this.link1Body.quaternion.x,
            this.link1Body.quaternion.y,
            this.link1Body.quaternion.z,
            this.link1Body.quaternion.w
        )

        this.link2Mesh.position.set(
            this.link2Body.position.x,
            this.link2Body.position.y,
            this.link2Body.position.z
        )
        this.link2Mesh.quaternion.set(
            this.link2Body.quaternion.x,
            this.link2Body.quaternion.y,
            this.link2Body.quaternion.z,
            this.link2Body.quaternion.w
        )

        this.link3Mesh.position.set(
            this.link3Body.position.x,
            this.link3Body.position.y,
            this.link3Body.position.z
        )
        this.link3Mesh.quaternion.set(
            this.link3Body.quaternion.x,
            this.link3Body.quaternion.y,
            this.link3Body.quaternion.z,
            this.link3Body.quaternion.w
        )
    }
}

const scene = new THREE.Scene()

new RGBELoader().load('/img/kloppenheim_06_puresky_1k.hdr', function (texture) {
    texture.mapping = THREE.EquirectangularReflectionMapping
    scene.environment = texture
})

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.01,
    100
)
camera.position.set(0.025, 1.25, 0.25)

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

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

const loader = new GLTFLoader()

await loader.loadAsync('/models/eve.glb').then((gltf) => {
    mixer = new THREE.AnimationMixer(gltf.scene)

    scene.add(gltf.scene)

    skeletonCollider = new SkeletonCollider(gltf.scene, world)

    const headBone = gltf.scene.getObjectByName('mixamorigHead') as THREE.Bone
    earingRight = new Earing(
        headBone,
        world,
        new THREE.Vector3(-0.055, 1.25, -0.02)
    )
    earingLeft = new Earing(
        headBone,
        world,
        new THREE.Vector3(0.055, 1.25, -0.02)
    )

    neckBone = gltf.scene.getObjectByName('mixamorigNeck') as THREE.Bone
})

loader.load('/models/eve@idle.glb', (gltf) => {
    // remove the animation track that controls the mixamorigNeck quaternion
    // so that I can control it with the mouse.
    // Otherwise the mixer overrides it.
    let i = 0
    const tracks = gltf.animations[0].tracks
    while (i < tracks.length) {
        if (tracks[i].name === 'mixamorigNeck.quaternion') {
            tracks.splice(i, 1)
        } else {
            ++i
        }
    }

    mixer.clipAction(gltf.animations[0]).play()
    ;(document.getElementById('spinner') as HTMLDivElement).style.display =
        'none'

    modelReady = true
})

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

const mouse = new THREE.Vector2()
function onMouseMove(event: MouseEvent) {
    mouse.set(
        (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    )

    neckBone && neckBone.lookAt(mouse.x - 0.1, mouse.y + 1.1, 1)
}
renderer.domElement.addEventListener('mousemove', onMouseMove, false)

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

const clock = new THREE.Clock()
let delta

const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

function animate() {
    if (modelReady) {
        delta = Math.min(clock.getDelta(), 0.1)

        skeletonCollider.update()
        earingLeft.update()
        earingRight.update()

        mixer.update(delta)

        world.step(delta)

        // uncomment to see the physics collision shapes
        //cannonDebugRenderer.update()
    }
    renderer.render(scene, camera)

    stats.update()
}

renderer.setAnimationLoop(animate)