Skip to content

Tween Material Properties

Description

Animating material properties is possible. In this example, if you hover over the polygons, then the colour, plus several other material properties are Tweened to new settings. This happens over a period of 100 milliseconds.

You can also click the polygon, and the scale will either increase or decrease depending on how it was left before the last click.

If you preferred to use lerp, then I also have a lerping version.

<>

Example Script

./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
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import TWEEN from '@tweenjs/tween.js'
// For missing typescript definition error see https://sbcode.net/threejs/tween/

const scene = new THREE.Scene()

const spotLight = new THREE.SpotLight(0xffffff, 500)
spotLight.position.set(5, 5, 5)
spotLight.angle = 0.3
spotLight.penumbra = 0.5
spotLight.castShadow = true
spotLight.shadow.mapSize.width = 512
spotLight.shadow.mapSize.height = 512
spotLight.shadow.bias = -0.001
spotLight.shadow.radius = 20
spotLight.shadow.blurSamples = 10
spotLight.shadow.camera.far = 15
scene.add(spotLight)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    100
)
camera.position.y = 2
camera.position.z = 4

// const helper = new THREE.CameraHelper(spotLight.shadow.camera)
// scene.add(helper)

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

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

const cube = new THREE.Mesh(
    new THREE.BoxGeometry(),
    new THREE.MeshPhysicalMaterial({ color: 0xff8800 })
)
cube.position.set(-2, 0, 0)
cube.castShadow = true
cube.userData.scaled = false
scene.add(cube)

const cylinder = new THREE.Mesh(
    new THREE.CylinderGeometry(0.66, 0.66),
    new THREE.MeshPhysicalMaterial({ color: 0x008800 })
)
cylinder.castShadow = true
cylinder.userData.scaled = false
scene.add(cylinder)

const pyramid = new THREE.Mesh(
    new THREE.TetrahedronGeometry(),
    new THREE.MeshPhysicalMaterial({ color: 0x0088ff })
)
pyramid.position.set(2, 0, 0)
pyramid.castShadow = true
pyramid.userData.scaled = false
scene.add(pyramid)

const texture = new THREE.TextureLoader().load('img/grid.png')

const envTexture = new THREE.CubeTextureLoader().load([
    'img/px_25.jpg',
    'img/nx_25.jpg',
    'img/py_25.jpg',
    'img/ny_25.jpg',
    'img/pz_25.jpg',
    'img/nz_25.jpg',
])
envTexture.mapping = THREE.CubeReflectionMapping
scene.environment = envTexture

const floor = new THREE.Mesh(
    new THREE.PlaneGeometry(10, 10),
    new THREE.MeshPhysicalMaterial()
) //{map:texture}))
floor.rotateX(-Math.PI / 2)
floor.position.y = -1.25
floor.receiveShadow = true
scene.add(floor)

const raycaster = new THREE.Raycaster()
let intersects: THREE.Intersection[]
const pickableObjects: THREE.Mesh[] = [cube, cylinder, pyramid]
let hoveredObject: null | THREE.Mesh = null
const wasHoveredObjects: THREE.Mesh[] = []

const originalMaterial = [
    cube.material.clone(),
    cylinder.material.clone(),
    pyramid.material.clone(),
]

const highlightedMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xff2244,
    reflectivity: 1.0,
    map: texture,
})

const mouse = new THREE.Vector2()
function onDocumentMouseMove(event: MouseEvent) {
    mouse.set(
        (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    )
    raycaster.setFromCamera(mouse, camera)
    intersects = raycaster.intersectObjects(pickableObjects, false)

    pickableObjects.forEach((o: THREE.Mesh, i) => {
        if (wasHoveredObjects.includes(o)) {
            wasHoveredObjects.splice(wasHoveredObjects.indexOf(o), 1)
            //console.log(wasHoveredObjects)
            new TWEEN.Tween((o.material as THREE.MeshPhysicalMaterial).color)
                .to(
                    {
                        r: originalMaterial[i].color.r,
                        g: originalMaterial[i].color.g,
                        b: originalMaterial[i].color.b,
                    },
                    100
                )
                .start()
            new TWEEN.Tween(o.material as THREE.MeshPhysicalMaterial)
                .to(
                    {
                        thickness: 0,
                        roughness: 1,
                        clearcoat: 0,
                        transmission: 0,
                        ior: 1.5,
                    },
                    100
                )
                .start()
        }
    })
    if (intersects.length) {
        const o = intersects[0].object as THREE.Mesh

        if (hoveredObject !== o) {
            if (hoveredObject !== null) {
                //currently something already hovered, so unhover it
                wasHoveredObjects.push(hoveredObject)
            }

            hoveredObject = o

            new TWEEN.Tween((o.material as THREE.MeshPhysicalMaterial).color)
                .to(
                    {
                        r: highlightedMaterial.color.r,
                        g: highlightedMaterial.color.g,
                        b: highlightedMaterial.color.b,
                    },
                    100
                )
                .start()
            new TWEEN.Tween(o.material as THREE.MeshPhysicalMaterial)
                .to(
                    {
                        thickness: 3.0,
                        roughness: 0.1,
                        clearcoat: 0.1,
                        transmission: 0.99,
                        ior: 1.1,
                    },
                    100
                )
                .start()
        }
    } else {
        // no intersects so nothing should be coloured as if hovered
        if (hoveredObject !== null) {
            wasHoveredObjects.push(hoveredObject)
            hoveredObject = null
        }
    }
}
document.addEventListener('mousemove', onDocumentMouseMove, false)

function onClick(event: MouseEvent) {
    raycaster.setFromCamera(mouse, camera)
    intersects = raycaster.intersectObjects(pickableObjects, false)

    if (intersects.length) {
        if (!intersects[0].object.userData.scaled) {
            intersects[0].object.userData.scaled = true
            new TWEEN.Tween((intersects[0].object as THREE.Mesh).scale)
                .to(
                    {
                        x: 1.5,
                        y: 1.5,
                        z: 1.5,
                    },
                    250
                )
                .start()
        } else {
            intersects[0].object.userData.scaled = false
            new TWEEN.Tween((intersects[0].object as THREE.Mesh).scale)
                .to(
                    {
                        x: 1.0,
                        y: 1.0,
                        z: 1.0,
                    },
                    250
                )
                .start()
        }
    }
}
renderer.domElement.addEventListener('pointerdown', onClick, false)

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

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

function animate() {
    requestAnimationFrame(animate)

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
    cylinder.rotation.x += 0.01
    cylinder.rotation.y += 0.01
    pyramid.rotation.x += 0.01
    pyramid.rotation.y += 0.01

    controls.update()

    //helper.update()

    TWEEN.update()

    render()

    stats.update()
}

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

animate()

Comments