【问题标题】:three.js - How to toggle camera position if mouse is clicked?three.js - 如果单击鼠标,如何切换相机位置?
【发布时间】:2017-03-04 10:21:52
【问题描述】:

我对 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; 设置为不同的特定位置。

【问题讨论】:

  • 请展示你的作品。到目前为止,您尝试过什么?
  • 添加到我的代码中。我尝试从这个tutorial 即兴创作,但这对我来说有点难以理解。我的主要问题是我不知道如何在单击鼠标时获取输入。我只想要一个简单的相机 z 轴上的相机样条动画,只要在我的场景上单击鼠标左键,它就会来回切换。

标签: javascript three.js perspectivecamera


【解决方案1】:

您可以在文档上监听鼠标事件,切换位置,然后调用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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2018-10-21
    • 2014-06-26
    • 2011-09-09
    • 2019-05-29
    • 2014-11-15
    • 2014-03-20
    相关资源
    最近更新 更多