简体   繁体   English

在three.js中检测球体和三角形之间的碰撞

[英]Detect collision between sphere and triangle in three.js

I wish to find whether a triangle collides at all with a sphere, in three.js 我想在three.js中找出三角形是否与球体发生碰撞

I have implemented a method using the raycaster and the sphere's vertices, but it is not working always because the triangle might be "between" 2 of the sphere's vertices and thus, not able to be detected. 我已经使用射线投射器和球体的顶点实现了一种方法,但是这种方法并不总是有效的,因为三角形可能在球体的两个顶点之间,因此无法被检测到。

I want a perfect mathematical algorithm. 我想要一个完美的数学算法。

Hey I have found the solution : 嘿,我找到了解决方案:

The algorithm works in 2 phases : 该算法分为两个阶段

Phase 1 阶段1

I create 3 lines using the 3 points I have from the triangle : 我使用三角形中的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
 }

and that's it for the lines of the triangle. 这就是三角形的线。 If no line intersects with the sphere, I will check the "body" of the triangle in Phase 2 : 如果没有线与球相交,我将在阶段2中检查三角形的“主体”:

Phase 2 阶段2

I create a THREE.Triangle using the 3 point sof the triangle, then I create a plane using that triangle and finally I find the closest point form the plane to the center of the sphere . 我使用三角形的3点创建了THREE.Triangle,然后使用该三角形创建了一个平面,最后找到了距该平面最接近球体中心的点。 If that point "belongs" to the triangle, we have a collision: 如果该点“属于”三角形,则发生碰撞:

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

If not collision is detected neither in Phase 1 or phase 2, the triangle does not collide with the sphere. 如果在阶段1或阶段2中都未检测到碰撞,则三角形不会与球体碰撞。

My solution has worked in my project perfectly. 我的解决方案在我的项目中运行良好。

Please inform for problems you may encounter. 请告知您可能遇到的问题。

我不建议您使用完美的数学算法,而是建议您看以下页面,据我所知,该页面完全涵盖了您的问题: Three.js-准确的射线投射以进行碰撞检测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM