Skip to content

Lerp

Video Lecture

Lerp Lerp

Description

Animating using Linear interpolation (Lerp).

There are many ways to lerp in Three.js from using the methods in the core base classes to even writing our own.

In this lesson, we will lerp an objects position, scale and material properties using various lerping options.

<>

Lesson Script

./src/main.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
import './style.css'
import {
  Mesh,
  Color,
  MeshStandardMaterial,
  BufferGeometry,
  Raycaster,
  Scene,
  SpotLight,
  PerspectiveCamera,
  WebGLRenderer,
  VSMShadowMap,
  BoxGeometry,
  CylinderGeometry,
  TetrahedronGeometry,
  PlaneGeometry,
  Vector2,
  Clock,
  EquirectangularReflectionMapping,
  MeshPhongMaterial,
  Vector3,
  MathUtils,
} from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'
import Stats from 'three/addons/libs/stats.module.js'

function lerp(from: number, to: number, speed: number) {
  const amount = (1 - speed) * from + speed * to
  return Math.abs(from - to) < 0.001 ? to : amount
}

class Pickable extends Mesh {
  hovered = false
  clicked = false
  colorTo: Color
  defaultColor: Color
  geometry: BufferGeometry
  material: MeshStandardMaterial
  v = new Vector3()

  constructor(geometry: BufferGeometry, material: MeshStandardMaterial, colorTo: Color) {
    super()
    this.geometry = geometry
    this.material = material
    this.colorTo = colorTo
    this.defaultColor = material.color.clone()
    this.castShadow = true
  }

  update(delta: number) {
    //this.rotation.x += delta / 2
    //this.rotation.y += delta / 2

    this.clicked ? (this.position.y = MathUtils.lerp(this.position.y, 1, delta * 5)) : (this.position.y = MathUtils.lerp(this.position.y, 0, delta * 5))

    //console.log(this.position.y)

    // this.clicked
    //   ? (this.position.y = lerp(this.position.y, 1, delta * 5))
    //   : (this.position.y = lerp(this.position.y, 0, delta * 5))

    // this.hovered
    //   ? this.material.color.lerp(this.colorTo, delta * 10)
    //   : this.material.color.lerp(this.defaultColor, delta * 10)

    // this.hovered
    //   ? (this.material.color.lerp(this.colorTo, delta * 10),
    //     (this.material.roughness = lerp(this.material.roughness, 0, delta * 10)),
    //     (this.material.metalness = lerp(this.material.metalness, 1, delta * 10))
    //     )
    //   : (this.material.color.lerp(this.defaultColor, delta),
    //     (this.material.roughness = lerp(this.material.roughness, 1, delta)),
    //     (this.material.metalness = lerp(this.material.metalness, 0, delta)))

    // this.clicked
    //   ? this.scale.set(
    //       MathUtils.lerp(this.scale.x, 1.5, delta * 5),
    //       MathUtils.lerp(this.scale.y, 1.5, delta * 5),
    //       MathUtils.lerp(this.scale.z, 1.5, delta * 5)
    //     )
    //   : this.scale.set(
    //       MathUtils.lerp(this.scale.x, 1.0, delta),
    //       MathUtils.lerp(this.scale.y, 1.0, delta),
    //       MathUtils.lerp(this.scale.z, 1.0, delta)
    //     )

    // this.clicked
    //   ? this.scale.set(
    //       lerp(this.scale.x, 1.5, delta * 5),
    //       lerp(this.scale.y, 1.5, delta * 5),
    //       lerp(this.scale.z, 1.5, delta * 5)
    //     )
    //   : this.scale.set(
    //       lerp(this.scale.x, 1.0, delta),
    //       lerp(this.scale.y, 1.0, delta),
    //       lerp(this.scale.z, 1.0, delta)
    //     )

    // this.clicked ? this.v.set(1.5, 1.5, 1.5) : this.v.set(1.0, 1.0, 1.0)
    // this.scale.lerp(this.v, delta * 5)
  }
}

const scene = new Scene()

const spotLight = new SpotLight(0xffffff, 500)
spotLight.position.set(5, 5, 5)
spotLight.angle = 0.3
spotLight.penumbra = 0.5
spotLight.castShadow = true
spotLight.shadow.radius = 20
spotLight.shadow.blurSamples = 20
spotLight.shadow.camera.far = 20
scene.add(spotLight)

await new RGBELoader().loadAsync('img/venice_sunset_1k.hdr').then((texture) => {
  texture.mapping = EquirectangularReflectionMapping
  scene.environment = texture
})

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

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

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

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.maxPolarAngle = Math.PI / 2 + Math.PI / 16 // ~ 100 degrees

const raycaster = new Raycaster()
const pickables: Pickable[] = [] // used in the raycaster intersects methods
let intersects
const mouse = new Vector2()

renderer.domElement.addEventListener('pointerdown', (e) => {
  mouse.set((e.clientX / renderer.domElement.clientWidth) * 2 - 1, -(e.clientY / renderer.domElement.clientHeight) * 2 + 1)

  raycaster.setFromCamera(mouse, camera)

  intersects = raycaster.intersectObjects(pickables, false)

  // toggles `clicked` property for only the Pickable closest to the camera
  intersects.length && ((intersects[0].object as Pickable).clicked = !(intersects[0].object as Pickable).clicked)

  // toggles `clicked` property for all overlapping Pickables detected by the raycaster at the same time
  // intersects.forEach((i) => {
  //   ;(i.object as Pickable).clicked = !(i.object as Pickable).clicked
  // })
})

// renderer.domElement.addEventListener('mousemove', (e) => {
//   mouse.set(
//     (e.clientX / renderer.domElement.clientWidth) * 2 - 1,
//     -(e.clientY / renderer.domElement.clientHeight) * 2 + 1
//   )

//   raycaster.setFromCamera(mouse, camera)

//   intersects = raycaster.intersectObjects(pickables, false)

//   pickables.forEach((p) => (p.hovered = false))

//   intersects.length && ((intersects[0].object as Pickable).hovered = true)
// })

const cylinder = new Pickable(new CylinderGeometry(0.66, 0.66), new MeshStandardMaterial({ color: 0x888888 }), new Color(0x008800))
scene.add(cylinder)
pickables.push(cylinder)

// const cube = new Pickable(
//   new BoxGeometry(),
//   new MeshStandardMaterial({ color: 0x888888 }),
//   new Color(0xff2200)
// )
// cube.position.set(-2, 0, 0)
// scene.add(cube)
// pickables.push(cube)

// const pyramid = new Pickable(
//   new TetrahedronGeometry(),
//   new MeshStandardMaterial({ color: 0x888888 }),
//   new Color(0x0088ff)
// )
// pyramid.position.set(2, 0, 0)
// scene.add(pyramid)
// pickables.push(pyramid)

const floor = new Mesh(new PlaneGeometry(20, 20), new MeshPhongMaterial())
floor.rotateX(-Math.PI / 2)
floor.position.y = -1.25
floor.receiveShadow = true
//floor.material.envMapIntensity = 0
scene.add(floor)

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

const clock = new Clock()
let delta = 0

function animate() {
  requestAnimationFrame(animate)

  delta = clock.getDelta()

  pickables.forEach((p) => {
    p.update(delta)
  })

  controls.update()

  renderer.render(scene, camera)

  stats.update()
}

animate()

Lerp with Epsilon

One problem with lerping, that may not ever be a problem for you, is that the destination/to of the lerp may never arrive, although it will be very close, and may appear to be correct. Lerping takes the current value, and the destination/to value, and moves it closer depending on the alpha value. The resulting difference will be a floating point number getting closer and closer to 0, but never actually reaching 0.

You can use this lerping function below, instead of MathUtils.lerp when you need your lerp to finish on the exact destination/to value. See the detail of the function, and you can see that it considers a minimum difference of .001. If the difference between the current value, and the destination/to value is less than .001, then it will return the desired destination/to value instead of the calculated value. The 0.001 is the Epsilon value that my function is using. You can replace it with a different minimum if you desire.

function lerp(from: number, to: number, speed: number) {
  const amount = (1 - speed) * from + speed * to
  return Math.abs(from - to) < 0.001 ? to : amount
}

You then replace any usage of MathUtils.lerp

this.clicked
    ? (this.position.y = MathUtils.lerp(this.position.y, 1, delta * 5))
    : (this.position.y = MathUtils.lerp(this.position.y, 0, delta * 5))

With the custom lerp.

this.clicked
    ? (this.position.y = lerp(this.position.y, 1, delta * 5))
    : (this.position.y = lerp(this.position.y, 0, delta * 5))

Linear_interpolation (wikipedia)

Color.lerp (threejs.org)

MathUtils.lerp (threejs.org)

Vector3.lerp (threejs.org)

Extending Classes