繁体   English   中英

如何在 ThreeJS 中单击鼠标的位置准确地绘制几何形状

[英]How to draw a geometry shape exactly where mouse is clicked in ThreeJS

我正在尝试在单击鼠标的位置准确地绘制一个圆圈,但在 position 处绘制的圆圈并不准确。 请让我知道代码中需要更正的内容:

            var camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
            camera.position.set( 0, 0, 1000 );


            document.addEventListener( 'mousedown', onDocumentMouseDown, false );

            function onDocumentMouseDown( event ) {
                event.preventDefault();


                if( event.which == 1) { // left mouse click

                   // x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
                   // y = - ( event.clientY / renderer.domElement.clientWidth ) * 2 + 1;

                    var x = event.clientX; // x coordinate of a mouse pointer
                    var y = event.clientY; // y coordinate of a mouse pointer
                    var rect = event.target.getBoundingClientRect();

                    x = ((x - rect.left) - window.innerWidth/2)/(window.innerWidth/2);
                    y = (window.innerHeight/2 - (y - rect.top))/(window.innerHeight/2);

                    var geometry = new THREE.CircleGeometry( 20, 32 );
                    var material = new THREE.MeshBasicMaterial( { color: 0x65A8FF } );
                    circle = new THREE.Mesh( geometry, material );

                    //circle.position.x = x*window.innerWidth*1.23;
                    //circle.position.y = y*765; 

                    circle.position.x = x*window.innerWidth;
                    circle.position.y = y*window.innerHeight;

                    scene.add( circle );
                }
            }

您的方法的问题在于它假设 3D xy坐标连接到像素坐标,而不考虑相机的视角或深度。 使用透视相机,点越深,它的 x、y 坐标就越大。 您需要为要停止的点设置深度 (z)。 此外,如果您的相机移动或旋转,您的X, Y坐标将不起作用。

我建议您使用THREE.Raycaster ,它会为您执行所有这些相机投影计算(文档在页面顶部有一个使用示例)。 您可以在此示例中看到该方法的实际效果。

它的工作方式是:

  1. 您为光线投射器创建一个平面(这是您的深度)。
  2. 使用 Raycaster.setFromCamera() 创建光线投射
  3. 回读光线击中平面的 position。
  4. 使用此 position 创建您的几何图形。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM