【问题标题】:THREE.js get GridHelper coordinates from MouseClickTHREE.js 从 MouseClick 获取 GridHelper 坐标
【发布时间】:2021-02-06 01:55:44
【问题描述】:

我如何获得 - 或 IN - 我正在点击的 GridHelper 的坐标?尤其是当Mesh 位于GridHelper 之上的实际地形时?

我的GridHelper 设置如下:

let  helperGrid = new THREE.GridHelper(600, 120, "yellow", “blue”);

所以每条网格线之间的距离是5(因为600 / 12 = 5)

当我在屏幕上点击时,我想知道我点击了网格中的哪个位置。例如,我是否单击了第一个方块中的某个地方?这意味着单击(对于 X 值)介于 (0, 0, 0) 和 (5, 0, 0) 之间的任意位置,以及对于介于 (0, 0, 0) 和 (0, 0, -5) 之间的任意位置的 Z 值?

我将尝试使用我点击的鼠标坐标来计算这个,我使用mousedown 事件以通常的方式计算:

mousePositionVector.x = (event.clientX / window.innerWidth) * 2 - 1;
mousePositionVector.y = -(event.clientY / window.innerHeight) * 2 + 1;
            

但这会转化为真正的微小十进制数字。例如,当我单击第一个网格框中的任意位置(即 x = 0 和 x = 5 之间)时,我得到的鼠标位置值如下:

 ( 0.07309721175584016 , 0.03186646433990892 )

或:

( 0.09269027882441594 , 0.02427921092564489 )

等等

同时,对应的 event.clientX 和 event.clientY 值 - 对于相同的点击事件 - 是:

clientXY = ( 740 , 634 ) 

因此,这两组价值观似乎都没有为我指明正确的方向。

除此之外,我想最终在这个网格上放置一个地形——这意味着我使用的rayCaster 将捕获我创建的地形Mesh 的顶点,这可能会使问题进一步复杂化。

解决这个问题的正确方法是什么?

【问题讨论】:

    标签: three.js coordinate-systems


    【解决方案1】:

    已经有一个演示与您的确切场景:Raycasting with a terrain mesh(单击右下角的<> 图标查看源代码)。

    当光线投射与地形网格相交时,它会返回一个具有以下属性的对象,as explained in the docs:{ distance, point, face, faceIndex, object },所以如果你想知道你悬停位置的x, z坐标,只需查看相交对象的.point 属性:

    function onMouseMove( event ) {
    
        // Get screen-space x/y
        mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
        mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
    
        // Perform raycast
        raycaster.setFromCamera( mouse, camera );
    
        // See if the ray from the camera into the world hits our mesh
        const intersects = raycaster.intersectObject( terrainMesh );
    
        // Check if an intersection took place
        if ( intersects.length > 0 ) {
            const posX = intersects[0].point.x;
            const posZ = intersects[0].point.z;
            console.log(posX, posZ);
        }
    
    }
    

    最后,如果你想知道以 5 个单位为增量的位置,只需做一点舍入技巧:

    const posX = Math.round(intersects[0].point.x / 5) * 5;
    const posZ = Math.round(intersects[0].point.z / 5) * 5;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2016-04-14
      • 2014-12-02
      • 2014-11-15
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多