首页 文章

three.js - 如果单击鼠标,如何切换摄像机位置?

提问于
浏览
0

我对three.js很新,所以如果这个问题看起来有些复杂,我很抱歉 .

所以我已经将我的场景设置为three.js,但是我想让我的相机的位置从A点平滑地动画到B点(我将在我的代码中指定A和B的位置) . 我可能会使用Tween.js来简化相机动画 .

我希望只要点击鼠标左键,我的相机就会发生位置变化 . 所以基本上,只要在场景的任何地方点击鼠标左键,摄像机的位置就会从位置A切换到位置B,反之亦然 .

但是,我不确定如何复制这样的东西 . 我找到了关于如何在按住鼠标时改变位置的教程,但是没有任何东西可以在固定位置来回切换位置,只要点击鼠标 . 我不知道是否要这样做我将不得不在我的代码的函数render()部分中创建一个'if'语句,表明如果单击鼠标来改变相机位置,但我想这太简单了?

任何帮助表示赞赏 .

编辑:

这是我的render()场景的代码:

function render() {

            var timer = Date.now() * 0.00030;

            camera.position.x += ( 0.5*Math.sin( timer ) * mouseX - camera.position.x ) * 0.05;
            camera.position.y += ( 0.5*Math.cos( timer ) *- mouseY - camera.position.y ) * 0.05;
            camera.position.z = 0;

            camera.lookAt( scene.position );

            for ( i = 0; i < scene.children.length; i ++ ) {
                var object = scene.children[ i ];
                if ( object instanceof THREE.Points ) {
                    object.rotation.y = time * ( i < 4 ? i + 1 : - ( i + 1 ) );
                }
            }

            for ( i = 0; i < materials.length; i ++ ) {
                color = parameters[i][0];
                h = ( 0 * ( color[0] + time ) % 360 ) / 360;
                materials[i].color.setHSL( h, color[1], color[2] );
            }

            renderer.render( scene, camera );

        }

为了澄清,我希望只要在我的场景上点击鼠标左键,就可以将 camera.position.z = 0; 设置为不同的特定位置 .

1 回答

  • 0

    您可以在文档上侦听鼠标事件,切换位置,然后调用 render() 重绘画布 .

    // list of positions in [x, y, z] coordinates
    var positions = [
      [0, 0, 0],
      [5, 0, 0]
    ];
    
    // set our first position
    var positionIndex = 0;
    var position = positions[positionIndex];
    
    document.addEventListener('click', function() {
      // when a click happens ...
      positionIndex++;
      // reset position index back to 0 if it's past the end of the array
      positionIndex = positionIndex >= positions.length ? 0 : positionIndex;
      
      // update the current position
      position = positions[positionIndex];
      
      // re-render the canvas
      render();
    });
    
    function render() {
      console.log('rendering at position', position);
    }
    
    
    // do our inital render
    render();
    

相关问题