如何在鼠标移动时重新创建 Three.js OrbitControl 移动?

a.b*_*eri 3 javascript perspectivecamera three.js

我想在没有单击和拖动的情况下重新创建 Three.js OrbitControl 运动,即简单地使相机跟随鼠标移动。

我试图从头开始重新创建它,但是太费力了,因为问题是相机在三个轴上移动,而不仅仅是两个。我很确定有些人以前做过。

具体来说,我希望相机围绕场景原点移动,并与它保持相同的距离。

tim*_*ray 6

我和OP有同样的要求。这就是我在Leeft评论的帮助下解决它的方法:

  1. 更新OrbitControls.js改变功能范围handleMouseMoveRotate

    function handleMouseMoveRotate( event )
    
    Run Code Online (Sandbox Code Playgroud)

    this.handleMouseMoveRotate = function ( event )
    
    Run Code Online (Sandbox Code Playgroud)

    这是您在自己的代码中手动使用此方法所必需的。

  2. 在加载模型的 JS 代码中,使用dispose方法删除默认鼠标控件并添加您自己的mousemove手动调用的事件处理程序handleMouseMoveRotate

    init();
    animate();
    
    function init() {
        // Set up Camera, Scene and OrbitControls
        camera = new THREE.PerspectiveCamera( 45, containerWidth / containerHeight );
        scene = new THREE.Scene();
        controls = new THREE.OrbitControls(camera);
    
        // Remove default OrbitControls event listeners
        controls.dispose();
        controls.update();
    
        ... // omitted for brevity: Load model and Renderer
    
        document.addEventListener('mousemove', onDocumentMouseMove, false);
    }
    
    function onDocumentMouseMove( event ) {
        // Manually fire the event in OrbitControls
        controls.handleMouseMoveRotate(event);
    }
    
    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    
    function render() {
        controls.update();
        camera.lookAt( scene.position );
        renderer.render( scene, camera );
    }
    
    Run Code Online (Sandbox Code Playgroud)

注意:此解决方案删除所有库侦听器。如果您有兴趣,可以再次启用它们,将它们从此处复制到更新方法的末尾。