Reputation: 542
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.
Upvotes: 1
Views: 1966
Reputation: 542
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.
Upvotes: 3
Reputation: 91
Instead of a perfect mathematical algorithm I can recommend you looking at the following page, that covers exactly your problem as far as I understand it: Three.js - Accurate ray casting for collision detection
Upvotes: -1