Rotate camera in Three.js with mouse

前端 未结 5 1718
心在旅途
心在旅途 2020-12-04 07:09

I have quite a few objects in my scene so rotating all of them could be a pain. So what is the most easy way to move camera around origin on mouse click and drag? This way a

5条回答
  •  庸人自扰
    2020-12-04 07:42

    Here's a project with a rotating camera. Looking through the source it seems to just move the camera position in a circle.

    function onDocumentMouseMove( event ) {
    
        event.preventDefault();
    
        if ( isMouseDown ) {
    
            theta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.5 )
                    + onMouseDownTheta;
            phi = ( ( event.clientY - onMouseDownPosition.y ) * 0.5 )
                  + onMouseDownPhi;
    
            phi = Math.min( 180, Math.max( 0, phi ) );
    
            camera.position.x = radious * Math.sin( theta * Math.PI / 360 )
                                * Math.cos( phi * Math.PI / 360 );
            camera.position.y = radious * Math.sin( phi * Math.PI / 360 );
            camera.position.z = radious * Math.cos( theta * Math.PI / 360 )
                                * Math.cos( phi * Math.PI / 360 );
            camera.updateMatrix();
    
        }
    
        mouse3D = projector.unprojectVector(
            new THREE.Vector3(
                ( event.clientX / renderer.domElement.width ) * 2 - 1,
                - ( event.clientY / renderer.domElement.height ) * 2 + 1,
                0.5
            ),
            camera
        );
        ray.direction = mouse3D.subSelf( camera.position ).normalize();
    
        interact();
        render();
    
    }
    

    Here's another demo and in this one I think it just creates a new THREE.TrackballControls object with the camera as a parameter, which is probably the better way to go.

    controls = new THREE.TrackballControls( camera );
    controls.target.set( 0, 0, 0 )
    

提交回复
热议问题