【发布时间】:2015-12-17 22:44:57
【问题描述】:
我希望在three.js中找到一个三角形是否与一个球体发生碰撞
我已经实现了一个使用光线投射器和球体顶点的方法,但它并不总是有效,因为三角形可能在球体顶点的“之间”2 个,因此无法被检测到。
我想要一个完美的数学算法。
【问题讨论】:
标签: javascript three.js collision-detection
我希望在three.js中找到一个三角形是否与一个球体发生碰撞
我已经实现了一个使用光线投射器和球体顶点的方法,但它并不总是有效,因为三角形可能在球体顶点的“之间”2 个,因此无法被检测到。
我想要一个完美的数学算法。
【问题讨论】:
标签: javascript three.js collision-detection
嘿,我找到了解决方案:
算法分2个阶段工作:
第一阶段
我使用三角形的 3 个点创建 3 条线:
var line1 = new THREE.Line3(a,b);
var line2 = new THREE.Line3(a,c);
var line3 = new THREE.Line3(b,c);
then I find the closest point from each of these 3 lines, to the center of the sphere :
var closestPoint1 = line1.closestPointToPoint(center, true);
var closestPoint2 = line2.closestPointToPoint(center, true);
var closestPoint3 = line3.closestPointToPoint(center, true);
then I calculate the distance of that point to the center :
// code for 1 line only
var distToCenter = closestPoint.distanceTo(center);
if(distToCenter <= radius){
// we have a collision
}
这就是三角形的线条。如果没有线与球体相交,我将在第 2 阶段检查三角形的“主体”:
第二阶段
我使用三角形的 3 点创建了一个 THREE.Triangle,然后使用该三角形创建了一个平面,最后我找到了从平面到球体中心的最近点。如果该点“属于”三角形,我们就会发生碰撞:
var triangle = new THREE.Triangle( a,b,c );
var plane = triangle.plane();
var pp, cp;
var dp = Math.abs(plane.distanceToPoint(center));
if(dp <= radius){
pp = plane.projectPoint(center);
cp = triangle.containsPoint(pp);
if(cp === true){
// collision
}
}
如果在阶段 1 或阶段 2 都没有检测到碰撞,则三角形不会与球体发生碰撞。
我的解决方案在我的项目中完美运行。
请告知您可能遇到的问题。
【讨论】:
我可以建议您查看以下页面,而不是完美的数学算法,据我了解,它完全涵盖了您的问题:Three.js - Accurate ray casting for collision detection
【讨论】: