Trying to implement a click to zoom feature with Three.js, I have a canvas and an object loaded in it. When clicking, I want to position the camera near the point of intersection for a zoom effect.
Here is my current code, but it's not working as expected. The camera position changes on click, but it only partially works. Sometimes the camera is placed near the intersection point, sometimes not.
onmousedown = function (event) {
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
event.preventDefault();
mouse.x = (event.clientX / self.renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / self.renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, self.camera);
var objects = [];
for (var i = 0; i < self.scene.children.length; i++) {
if (self.scene.children[i] instanceof THREE.Group) {
objects.push(self.scene.children[i]);
}
}
console.log(objects);
var intersects = raycaster.intersectObjects( objects,true );
console.log(intersects.length);
if (intersects.length > 0) {
self.camera.up = new THREE.Vector3(0, 0, 1);
self.camera.lookAt(new THREE.Vector3(0, 0, 0));
self.camera.position.z = intersects[0].point.z * .9;
self.camera.position.x = intersects[0].point.x * .9;
self.camera.position.y = intersects[0].point.y * .9;
}
};
Using a global
viewer object called self
which contains camera, canvas, and various other objects.
The number 0.9
is simply a value used to position the camera near the intersection point.
The camera used is a PerspectiveCamera
and the controls are TrackballControls
.
new THREE.PerspectiveCamera(90, this.width / this.height, 1, 1000);
The objects loaded are from .obj or .dae files. The expected behavior is to click on any point of the object and have the camera move near that point. However, the camera sometimes doesn't move near the clicked point.
- Does
intersects[0]
give the nearest intersection point, or the nearest in the direction of the camera? - Where am I going wrong in this implementation?
I am new to Three.js and just starting to learn. Please point out any mistakes or logical errors in my code.