grzesiekmq
grzesiekmq

Reputation: 429

threejs lerp and camera the animation is not smooth

what is the problem with linear interpolation?
in update() in case this is animate() and when I call zoomCamera() in update() there is lerp with smooth but when I call here

function onObjectsClick(event) {
            event.preventDefault();
            setPickPosition(event);
            raycasting(pickPosition, scene, camera);
            pickedObject = intersectedObjects[0].object;
            const notebook = pickedObject.getObjectByName('notebook');
            const laptop = pickedObject.getObjectByName('laptop');

            if (notebook || laptop) {

                zoomCamera();
            }

        }
canvas.addEventListener('click', onObjectsClick, false);

in if there is no smooth lerp but sharp transition what I miss?

function zoomCamera() {
            const vec = new THREE.Vector3(-1, 2, 2);
            const alpha = .1;
            camera.position.lerp(vec, alpha);
            console.log('zoom');
        }

and the onObjectsClick is in animate()
why it is happened?

Upvotes: 1

Views: 4405

Answers (1)

M -
M -

Reputation: 28472

Don't include your OnObjectsClick() function inside your animation loop, this is going to make your system haywire because it will probably create 60 versions of the same function per second.

Also, don't create a new THREE.Vector3 each time you call the zoomCamera() function. Instead, create one target, and have the camera constantly lerping towards that target in your animation loop. When you've detected a click, change the value of the camera's target position. Like this:

// Set camera to original position
var cameraTarget = new THREE.Vector3(3, 4, 4);

// Click listener goes outside animation loop
function onObjectsClick(event) {

    // ...

    if (notebook || laptop) {
        // When conditions are met, change target position
        cameraTarget.set(-1, 2, 2);
    }

    // ...

}

animate() {
    // Camera will lerp closer to target on each frame
    camera.position.lerp(cameraTarget, 0.1);
    renderer.render(scene, camera);
    requestAnimationFrame(animate);
}

Upvotes: 5

Related Questions