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();
}
这就是我所看到的:
答案 0 :(得分:1)
首先要注意的是hits[].points
会返回光标正下方的一个点,但它不会“捕捉”到点。
为了获得该点的实际位置,我们需要首先使用hits[].index
来获取我们点击的点/顶点的索引号。然后我们可以使用GEOMETRY.vertices[]
直接访问该顶点,THREE.Vector3
返回我们使用我们的光线投射点击的顶点的GEOMETRY.vertices[hits[i].index]
。
因此,通过输入索引,我们可以得到我们的光线投射命中的每个顶点的确切位置:
THREE.LineSegments
这为顶点提供了基本的“捕捉”。
注意:使用GEOMETRY.vertices[hits[i+1].index]
时,结果将始终是起始点,而不是结束点。要获得结束点,您只需将1添加到索引值:
// 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
要直接捕捉到与光标最近的顶点,我们需要找到距离raycaster射线最短垂直距离的顶点。为此,我们使用2个向量的叉积。这不仅仅是一个数学概念,而是一个编程概念,所以如果你想了解其背后的原因,请查找类似的东西:从一个点到一条直线的垂直距离
我刚从这个问题中取出代码并将其翻译出来:http://answers.unity3d.com/questions/568773/shortest-distance-from-a-point-to-a-vector.html
最终结果:
/blog
结果如下:)