Skip to content

Examples : Finger Physics

Description

<>

This example demonstrates,

  • Using Cannon.js as the Physics engine
  • Using CANNON.Heightfield
  • Auto generating a CANNON.Heightfield using a THREE.Raycaster to find the heights of an object when loaded into the scene.

Code

./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
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
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, 300)
light1.position.set(10, 10, -10)
light1.angle = Math.PI / 4
light1.penumbra = 0.5
light1.castShadow = true
light1.shadow.mapSize.width = 2048
light1.shadow.mapSize.height = 2048
light1.shadow.camera.near = 10
light1.shadow.camera.far = 30
light1.shadow.bias = 0.001
scene.add(light1)

const light2 = new THREE.SpotLight(0xffffff, 300)
light2.position.set(-10, 10, -10)
light2.angle = Math.PI / 4
light2.penumbra = 0.5
light2.castShadow = true
light2.shadow.mapSize.width = 2048
light2.shadow.mapSize.height = 2048
light2.shadow.camera.near = 10
light2.shadow.camera.far = 30
light2.shadow.bias = 0.001
scene.add(light2)

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

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

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

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

const material = new THREE.MeshStandardMaterial({
    color: 0xffffff,
    roughness: 0.05,
    metalness: 0.54,
    flatShading: true,
})
const handMaterial = new THREE.MeshStandardMaterial({
    color: 0xffffff,
    roughness: 0.05,
    metalness: 0.54,
    flatShading: true,
    transparent: true,
    opacity: 0.9,
})
const pmremGenerator = new THREE.PMREMGenerator(renderer)
const envTexture = new THREE.TextureLoader().load(
    'img/pano-equirectangular.jpg',
    () => {
        material.envMap = pmremGenerator.fromEquirectangular(envTexture).texture
    }
)

let hand: THREE.Group
let bowl: THREE.Mesh
let fingerBody: CANNON.Body

const gltfLoader = new GLTFLoader()
gltfLoader.load(
    'models/right-hand-bent.glb',
    function (gltf) {
        hand = gltf.scene
        hand.children[0].position.set(0.95, 4, 0.85)
        hand.children[0].receiveShadow = true
        hand.children[0].castShadow = true
        ;(hand.children[0] as THREE.Mesh).material = handMaterial

        scene.add(gltf.scene)

        fingerBody = new CANNON.Body({ mass: 0 })
        fingerBody.addShape(new CANNON.Sphere(0.25))
        fingerBody.addShape(
            new CANNON.Sphere(0.25),
            new CANNON.Vec3(0.05, 0.5, 0.1)
        )
        fingerBody.addShape(
            new CANNON.Sphere(0.25),
            new CANNON.Vec3(0.1, 1.0, 0.2)
        )
        fingerBody.position.set(0, 0, 0)
        world.addBody(fingerBody)

        const objLoader = new OBJLoader()
        objLoader.load(
            'models/bowl.obj',
            function (obj) {
                bowl = obj.children[0] as THREE.Mesh
                bowl.receiveShadow = true
                bowl.material = material
                scene.add(bowl)

                // using the raycaster to generate a cannon height field based on
                // the loaded bowl geometry
                const raycaster = new THREE.Raycaster()
                const down = new THREE.Vector3(0, -1, 0)
                const matrix: number[][] = []
                for (let x = -10; x <= 10; x++) {
                    matrix.push([])
                    for (let z = -10; z <= 10; z++) {
                        raycaster.set(new THREE.Vector3(x, 10, z), down)
                        const intersects = raycaster.intersectObject(
                            bowl,
                            false
                        )
                        if (intersects.length > 0) {
                            matrix[x + 10][z + 10] = intersects[0].point.y
                        } else {
                            matrix[x + 10][z + 10] = 0
                        }
                    }
                }

                let bowlBody = new CANNON.Body({ mass: 0 })
                var bowlShape = new CANNON.Heightfield(matrix)
                bowlBody.quaternion.setFromAxisAngle(
                    new CANNON.Vec3(1, 0, 0),
                    -Math.PI / 2
                )
                bowlBody.addShape(bowlShape, new CANNON.Vec3())
                bowlBody.position.x = -10
                bowlBody.position.z = 10
                world.addBody(bowlBody)

                renderer.domElement.addEventListener(
                    'mousemove',
                    onMouseMove,
                    false
                )
            },
            (xhr) => {
                console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
            },
            (error) => {
                console.log(error)
            }
        )
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log(error)
    }
)

const ballCount = 100
const sphereMesh: THREE.Mesh[] = new Array()
const sphereBody: CANNON.Body[] = new Array()
for (let i = 0; i < ballCount; i++) {
    const sphereGeometry = new THREE.SphereGeometry(0.5, 8, 8)
    sphereMesh.push(new THREE.Mesh(sphereGeometry, material))
    sphereMesh[i].position.x = Math.random() * 10 - 5
    sphereMesh[i].position.y = i / 4 + 4
    sphereMesh[i].position.z = Math.random() * 10 - 5
    sphereMesh[i].castShadow = true
    sphereMesh[i].receiveShadow = true
    scene.add(sphereMesh[i])
    const sphereShape = new CANNON.Sphere(0.5)
    sphereBody.push(new CANNON.Body({ mass: 0.1 }))
    sphereBody[i].addShape(sphereShape)
    sphereBody[i].position.x = sphereMesh[i].position.x
    sphereBody[i].position.y = sphereMesh[i].position.y
    sphereBody[i].position.z = sphereMesh[i].position.z
    world.addBody(sphereBody[i])
}

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

const raycaster = new THREE.Raycaster()

let fingerTo = new THREE.Vector3()

function onMouseMove(event: MouseEvent) {
    const mouse = {
        x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1,
    }

    raycaster.setFromCamera(mouse, camera)

    const intersects = raycaster.intersectObject(bowl, false)

    if (intersects.length > 0) {
        fingerTo.copy(intersects[0].point)
    }
}

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

const clock = new THREE.Clock()
let delta

const cannonDebugRenderer = new CannonDebugRenderer(scene, world)

function animate() {
    requestAnimationFrame(animate)
    controls.update()

    delta = clock.getDelta()
    if (delta > 0.1) delta = 0.1
    world.step(delta)

    if (hand) {
        hand.position.copy(fingerTo)
        fingerBody.position.set(
            hand.position.x,
            hand.position.y + 0.66,
            hand.position.z
        )
        for (let i = 0; i < ballCount; i++) {
            sphereMesh[i].position.set(
                sphereBody[i].position.x,
                sphereBody[i].position.y,
                sphereBody[i].position.z
            )
            sphereMesh[i].quaternion.set(
                sphereBody[i].quaternion.x,
                sphereBody[i].quaternion.y,
                sphereBody[i].quaternion.z,
                sphereBody[i].quaternion.w
            )
        }
    }

    //un-commment next line to see the cannon debug renderer shapes
    //cannonDebugRenderer.update()

    render()

    stats.update()
}

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

animate()

Comments