首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >三个JS光线投射--找到离光标最近的点

三个JS光线投射--找到离光标最近的点
EN

Stack Overflow用户
提问于 2017-05-13 11:44:01
回答 1查看 1.7K关注 0票数 2

Three.js r85

当用三个JS进行光线投射时,会返回一系列点,我想找到离光标最近的点。返回的第一点似乎是离摄像机最近的点。

有办法找到光标位置和点之间的距离吗?

下面是我现在用来调试这个程序的代码:

代码语言:javascript
复制
var raygun = new THREE.Raycaster();
raygun.setFromCamera(mouse, camera);
var hits = raygun.intersectObjects([plotpoints]);

if (hits.length > 0) {
    scope.remove(dotPlot);
    scope.remove(dotPlot2);

    // All points except the first one - Grey
    dotGeo = new THREE.Geometry();
    for (var i=1; i < hits.length; i++) {
        dotGeo.vertices.push(plotpoints.geometry.vertices[hits[i].index]);
    }
    dotPlot = new THREE.Points(dotGeo, dotMat);
    scope.add(dotPlot);

    // First point - Orange
    var geo2 = new THREE.Geometry();
    geo2.vertices.push(plotpoints.geometry.vertices[hits[0].index]);
    dotPlot2 = new THREE.Points(geo2, dotMat2);
    scope.add(dotPlot2);

    scope.render();
}

我现在看到的是:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-13 13:24:57

啊,用数学算出来的!

首先要注意的是,hits[].points直接返回光标下的一个点,但它不会“快速”到点。

为了得到点的实际位置,我们需要首先使用hits[].index得到点/顶点的索引数。然后,我们可以使用GEOMETRY.vertices[]直接访问这个顶点,它返回我们用光线投射击中的顶点的THREE.Vector3

因此,通过在索引中添加信息,我们可以得到光线投射的每个顶点的确切位置:

GEOMETRY.vertices[hits[i].index]

这为顶点提供了基本的“抓取”。

注意:当使用THREE.LineSegments时,结果始终是起点,而不是终点。要获得结束点,只需将1添加到索引值:

GEOMETRY.vertices[hits[i+1].index]

要想直接拍摄到离光标最近的顶点,我们需要找到与光线垂直距离最短的顶点。为了做到这一点,我们使用了两个向量的交叉积。这更像是一个数学概念,而不是编程概念,因此,如果您想要了解背后的原因,请查找以下内容:从点到线的垂直距离。

我只是从这个问题中提取了代码并翻译了它:http://answers.unity3d.com/questions/568773/shortest-distance-from-a-point-to-a-vector.html

最后的结果是:

代码语言:javascript
复制
// Variables to record and compare
var smallestDist = 99;
var smallestPointIndex = 0;

// Declare variables outside of loop to save memory
var m_ray = raycaster.ray;
var raydir = m_ray.direction; 
var origin = m_ray.origin;
var hitray = new THREE.Vector3(0,0,0);
var dist = 1;

// Loop over all points to find the closest
for (var i=0; i<hits.length; i++){
    // Math is magic
    hitray.subVectors(plotpoints.geometry.vertices[hits[i].index], origin);
    dist = new THREE.Vector3().crossVectors(raydir, hitray).lengthSq();

    // Record the closest point
    if (dist < smallestDist) {
        smallestDist = dist;
        smallestPointIndex = i;
    }
}

// Now we can use that single point

结果如下:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43952747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档