My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse button, causing the camera to zoom in again. I tried using a "dragged" variable with nested if statements to solve this problem, but it's not working as expected. Can anyone suggest a solution?
var mesh=[];
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2()
function onClick(event) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( scene.children, true );
var dragged = false
window.addEventListener('mousedown', function () { dragged = false })
window.addEventListener('mousemove', function () { dragged = true })
window.addEventListener('mouseup', function() {
if (dragged == true) { return }
//Click Tree006 to focus
if ( intersects.length > 0 && intersects[0].object.name==="Tree006") {
var object = intersects[0].object;
zoomInTimeline(mesh["Tree006"].position.x, mesh["Tree006"].position.y, mesh["Tree006"].position.z, 5);
console.log( 'Intersection:', intersects[ 0 ] );
}
//Click anywhere outside of object to leave focus
if ( intersects.length > 0 && intersects[0].object.name!=="Tree006") {
var object = intersects[0].object;
gsap.to( camera.position, {
duration: 1, // seconds
x: 6,
y: 4,
z: 4,
onUpdate: function() {
controls.enabled = true;
// controls.enableRotate = true;
}
} );
}
//Click object to focus
if ( intersects.length > 0 && intersects[0].object.name==="Tree001") {
var object = intersects[0].object;
zoomInTimeline(mesh["Tree001"].position.x, mesh["Tree001"].position.y, mesh["Tree001"].position.z, 5);
console.log( 'Intersection:', intersects[ 0 ] );
}
//Click anywhere outside of object to leave focus
if ( intersects.length > 0 && intersects[0].object.name!=="Tree001") {
var object = intersects[0].object;
gsap.to( camera.position, {
duration: 1, // seconds
x: 6,
y: 4,
z: 4,
onUpdate: function() {
controls.enabled = true;
// controls.enableRotate = true;
}
} );
}
})
}