Canceling Camera Damping Effect on Click in a 3D Scene

45 views Asked by At

I’m working on a project where I want the camera to have a damping effect when the user stops rotating it using the mouse. This effect is desired, but I would also like to provide users with an option to cancel the damping effect by clicking on the screen.

I’ve tried the following code to disable and re-enable the controls and damping onClick event:

this.control.enabled = false;
this.control.enableDamping = false;
this.control.update();
this.control.enableDamping = true;
this.control.enabled = true;

However, this approach doesn’t work as expected. When the user clicks to cancel the damping effect, the camera suddenly jumps to a different position, as if it’s completing the calculation and moving to the latest update.

Any suggestions on how to achieve the desired behavior would be greatly appreciated. Thanks!

1

There are 1 answers

0
AndTheGodsMadeLove On

Since the controls need to be updated to grant a flawless damping you have to update the controls in your "render loop". Simply check if damping is enabled within your loop and update the controls conditionaly.

Following snippet demonstrates this by togglin' damping with a doubleclick.

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

const canvas = document.querySelector('canvas.webgl')

const scene = new THREE.Scene()

const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 'lightblue' })
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

const width = 800;
const height = 600;

const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 10)
camera.position.set(1, 1, 3);
scene.add(camera)

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

const renderer = new THREE.WebGLRenderer({
    canvas: canvas
});
renderer.setSize(width, height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

const loop = () =>
{
    if (controls.enableDamping) {
        controls.update()
    }

    renderer.render(scene, camera)

    window.requestAnimationFrame(loop)
}

loop()

canvas.addEventListener('dblclick', () => controls.enableDamping = !controls.enableDamping)