Search code examples
three.jsorbitcontrols

three js zooming in where the cursor is using orbit controls


I'm very new to three js and is currently trying to implement a feature where the user can zoom in where the cursor is. The plan is to use a raycaster to get the point of intersection and then and use it to update the vector of the orbit controls every time the cursor moves.

the orbit control is initialized like so

        this.controls = new OrbitControls( this.camera_, this.threejs_.domElement );
        this.controls.listenToKeyEvents( window ); 
        
        this.controls.screenSpacePanning = false;

        this.controls.minDistance = 30;
        this.controls.maxDistance = 500;

        this.controls.maxPolarAngle = Math.PI / 2;

this is the eventlistener

        document.addEventListener('pointermove', (e) => this.onPointerMove(e), false);

and the onPointerMove function looks like this

    onPointerMove(event){
        const pointer = {
            x: (event.clientX / window.innerWidth) * 2 - 1,
            y: -(event.clientY / window.innerHeight) * 2 + 1,
        }
        this.rayCaster.setFromCamera( pointer, this.camera_);
        const intersects = this.rayCaster.intersectObjects( this.scene_.children, false);
        if ( intersects.length > 0 ) {
            this.controls.target(intersects[0].point);
            this.controls.update();
        }
    }

so far, intersects[0].point seems to be getting the intersect coordinate correctly but the orbit control is simply not getting updated. I have also tried changing the camera's position using

this.camera_.position.set(intersects[0].point.x+20,intersects[0].point.y+20,intersects[0].point.z+20);            

this.controls.update();

however that just moves my camera everywhere i point.

Edit: this doesnt work either

            const newTarget = new Vector3(intersects[0].point.x,intersects[0].point.y,intersects[0].point.z);
            this.controls.target.copy(newTarget);

Solution

  • found the answer here. Apparently you need to use either copy or set to change the target of the orbit controls. Without calling update().
    like so

    this.controls.target.set(intersects[0].point.x,intersects[0].point.y,intersects[0].point.z);