Skip to content

Examples : Bouncing Dice

Description

This example demonstrates,

  • Using a CANNON.Trimesh as a container object.
  • Creating a rolling die with physics properties, and 6 textures for each side.
  • Simulating bouncing the dice off the floor on button click.
  • Soft shadows.
  • Using a custom CANNON.Material
<>

The problem to solve in this example was how to collide each dice CANNON.Box shape with the containers CANNON.Trimesh shape.

CANNON.Trimesh can't collide with CANNON.Box shapes, but can collide with CANNON.Sphere and CANNON.Plane. See Supported Cannon.js Shape Collisions

So, to solve this, each dice uses a compound shape of a CANNON.Box and CANNON.Sphere.

Compound Box Sphere

Each Dice will collide with each other using their CANNON.Box.

They will also collide with the bouncer object, which is a CANNON.Cylinder.

When a die bounces and hits the container wall, it will use its CANNON.Sphere, since it can collide with a CANNON.Trimesh.

./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
<!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 :
            https://sbcode.net/threejs
        </title>
        <style>
            body {
                overflow: hidden;
                margin: 0px;
            }

            #bounceButton {
                height: 50px;
                width: 200px;
                margin: -25px -100px;
                position: absolute;
                bottom: 10%;
                left: 50%;
                font-size: 32px;
            }
        </style>
    </head>

    <body>
        <button id="bounceButton">Bounce</button>
        <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
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import * as CANNON from 'cannon-es'
import CannonUtils from './utils/cannonUtils'
// import CannonDebugRenderer from './utils/cannonDebugRenderer'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'
import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry'
import TWEEN from '@tweenjs/tween.js'

class Dice {
    mesh: THREE.Mesh
    static textureLoader = new THREE.TextureLoader()

    body: CANNON.Body

    constructor(
        scene: THREE.Scene,
        world: CANNON.World,
        position: CANNON.Vec3
    ) {
        const materials = [
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-1.png'),
            }),
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-2.png'),
            }),
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-3.png'),
            }),
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-4.png'),
            }),
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-5.png'),
            }),
            new THREE.MeshStandardMaterial({
                map: Dice.textureLoader.load('img/dice-6.png'),
            }),
        ]
        this.mesh = new THREE.Mesh(
            new RoundedBoxGeometry(1, 1, 1, 1, 0.2),
            materials
        )
        this.mesh.castShadow = true
        scene.add(this.mesh)

        this.body = new CANNON.Body({ mass: 1, material: diceMaterial })
        this.body.addShape(new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5)))
        this.body.addShape(new CANNON.Sphere(0.5))
        this.body.position.copy(position)
        world.addBody(this.body)
    }

    update() {
        this.mesh.position.set(
            this.body.position.x,
            this.body.position.y,
            this.body.position.z
        )
        this.mesh.quaternion.set(
            this.body.quaternion.x,
            this.body.quaternion.y,
            this.body.quaternion.z,
            this.body.quaternion.w
        )
    }
}

class Floor {
    body: CANNON.Body
    constructor(scene: THREE.Scene, world: CANNON.World) {
        const geometry = new THREE.PlaneGeometry(25, 25)
        const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial())
        mesh.rotateX(-Math.PI / 2)
        mesh.receiveShadow = true
        scene.add(mesh)

        const shape = new CANNON.Plane()
        this.body = new CANNON.Body({ mass: 0 })
        this.body.addShape(shape)
        this.body.quaternion.setFromAxisAngle(
            new CANNON.Vec3(1, 0, 0),
            -Math.PI / 2
        )
        world.addBody(this.body)
    }
}

class Bouncer {
    mesh: THREE.Mesh
    body: CANNON.Body
    constructor(scene: THREE.Scene, world: CANNON.World) {
        const geometry = new THREE.CylinderGeometry(5, 5, 0.5, 32)
        this.mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial())
        this.mesh.position.y = 0.25
        this.mesh.castShadow = true
        this.mesh.receiveShadow = true
        scene.add(this.mesh)

        const shape = new CANNON.Cylinder(5, 5, 0.5, 8)
        this.body = new CANNON.Body({ mass: 0, material: bouncerMaterial })
        this.body.addShape(shape)
        this.body.position.x = this.mesh.position.x
        this.body.position.y = this.mesh.position.y
        this.body.position.z = this.mesh.position.z
        world.addBody(this.body)
    }
    update() {
        this.mesh.position.set(
            this.body.position.x,
            this.body.position.y,
            this.body.position.z
        )
        this.mesh.quaternion.set(
            this.body.quaternion.x,
            this.body.quaternion.y,
            this.body.quaternion.z,
            this.body.quaternion.w
        )
    }
}

class Cover {
    constructor(scene: THREE.Scene, world: CANNON.World) {
        const loader = new GLTFLoader()
        loader.load(
            'models/cover.glb',
            function (gltf) {
                gltf.scene.traverse(function (child) {
                    if ((child as THREE.Mesh).isMesh) {
                        if (child.name === 'Cover') {
                            ;(child as THREE.Mesh).material =
                                new THREE.MeshPhysicalMaterial({
                                    metalness: 0,
                                    roughness: 0.01,
                                    transmission: 0.99,
                                    ior: 1.2,
                                })
                            scene.add(child)

                            const body = new CANNON.Body({ mass: 0 })
                            const shape = CannonUtils.CreateTrimesh(
                                (child as THREE.Mesh).geometry
                            )
                            body.addShape(shape)
                            world.addBody(body)
                        }
                    }
                })
            },
            (xhr) => {
                console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
            },
            (error) => {
                console.log(error)
            }
        )
    }
}

const scene = new THREE.Scene()

const light = new THREE.DirectionalLight()
light.position.set(10, 5, 2)
light.castShadow = true
light.shadow.mapSize.width = 256
light.shadow.mapSize.height = 256
light.shadow.camera.near = 0.5
light.shadow.camera.far = 25
light.shadow.camera.left = -10
light.shadow.camera.right = 10
light.shadow.camera.top = 10
light.shadow.camera.bottom = -10
light.shadow.radius = 5
light.shadow.blurSamples = 25

scene.add(light)

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.1,
    1000
)
camera.position.set(5, 7, 7)

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

const controls = new OrbitControls(camera, renderer.domElement)
controls.target.set(0, 2, 0)

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

const diceMaterial = new CANNON.Material('diceMaterial')
const bouncerMaterial = new CANNON.Material('bouncerMaterial')
const contactMaterial = new CANNON.ContactMaterial(
    diceMaterial,
    bouncerMaterial,
    {
        friction: 1,
        restitution: 0.5,
    }
)
world.addContactMaterial(contactMaterial)

const dice = [
    new Dice(scene, world, new CANNON.Vec3(1, 2, 0)),
    new Dice(scene, world, new CANNON.Vec3(0, 2, 1)),
    new Dice(scene, world, new CANNON.Vec3(-1, 2, 0)),
    new Dice(scene, world, new CANNON.Vec3(0, 2, -1)),
    new Dice(scene, world, new CANNON.Vec3(1.5, 4, 0)),
    new Dice(scene, world, new CANNON.Vec3(0, 4, 1.5)),
    new Dice(scene, world, new CANNON.Vec3(-1.5, 4, 0)),
    new Dice(scene, world, new CANNON.Vec3(0, 4, -1.5)),
]

new Floor(scene, world)

const bouncer = new Bouncer(scene, world)

new Cover(scene, world)

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

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

const bounceButton = document.getElementById('bounceButton') as HTMLInputElement
bounceButton.addEventListener(
    'click',
    function () {
        for (const d of dice) {
            d.body.position.y < 1.25 &&
                d.body.applyImpulse(new CANNON.Vec3(0, 30, 0))
        }

        new TWEEN.Tween(bouncer.body.position)
            .to(
                {
                    y: 1,
                },
                1
            )
            .start()
            .onComplete(() => {
                new TWEEN.Tween(bouncer.body.position)
                    .to(
                        {
                            y: 0.25,
                        },
                        30
                    )
                    .start()
            })
    },
    false
)

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

function animate() {
    requestAnimationFrame(animate)

    controls.update()

    for (const d of dice) {
        d.update()
    }
    bouncer.update()

    // cannonDebugRenderer.update()

    world.fixedStep()

    TWEEN.update()

    render()

    stats.update()
}

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

animate()

Comments