简体   繁体   中英

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

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

I create 3 lines using the 3 points I have from the triangle :

 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 :

Phase 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 . 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.

My solution has worked in my project perfectly.

Please inform for problems you may encounter.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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