gpt4 book ai didi

javascript - 三个JS Raycasting - 找到离光标最近的点

转载 作者:行者123 更新时间:2023-11-29 23:46:16 24 4
gpt4 key购买 nike

Three.js r85

用Three JS进行光线转换时,返回一系列点,我想找到离光标最近的点。返回的第一个点似乎是离相机最近的点。

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

这是我现在用来调试的代码:

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();
}

这是我所看到的:

First point is not close to cursor

最佳答案

啊,用数学算出来了!

首先要注意的是,hits[].points 返回光标正下方的一个点,但它不会“捕捉”到点。

为了得到点的实际位置,我们需要先使用hits[].index来得到我们命中的点/顶点的索引号.然后,我们可以使用 GEOMETRY.vertices[] 直接访问该顶点,它返回我们用光线转换命中的顶点的 THREE.Vector3

因此,通过输入索引,我们可以获得光线转换命中的每个顶点的确切位置:
GEOMETRY.vertices[hits[i].index]

这为顶点提供了基本的“捕捉”。

注意:当使用 THREE.LineSegments 时,结果将始终是起点,而不是终点。要得到终点,只需将索引值加 1 即可:
GEOMETRY.vertices[hits[i+1].index]

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

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

最终结果:

// 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

这是结果:)

Success

关于javascript - 三个JS Raycasting - 找到离光标最近的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com