Advertisement
Guest User

Ray Triangle Intersect Java

a guest
May 24th, 2016
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. /**
  2. * Precision collision detection between a ray and a triangle.
  3. * @param origin - origin of the picking ray
  4. * @param far_point - far collision of the picking ray
  5. * @param point_a - the triangle's vertex0
  6. * @param point_b - the triangle's vertex1
  7. * @param point_c - the triangle's vertex2
  8. * @return - the location of the intersection, as Vector3, else null for no collision
  9. */
  10. public static Vector3 rayTriangleIntersect(Vector3 origin, Vector3 far_point, Vector3 point_a, Vector3 point_b, Vector3 point_c)
  11. {
  12. Vector3 normal, point_intersect, test_vector;
  13.  
  14. //find the triangles normal
  15. normal = (point_b.subtract(point_a).normalize().crossProduct((point_c.subtract(point_a).normalize())));
  16.  
  17. //find the distance from origin to the triangle
  18. float dist1 = (origin.subtract(point_a).dotProduct(normal));
  19.  
  20. //find the distance from far_point to the triangle
  21. float dist2 = (far_point.subtract(point_a).dotProduct(normal));
  22.  
  23. //check to see if the ray intersects the triangle
  24. if((dist1 * dist2) >= 0.0f) return null;//it doesn't
  25.  
  26. //check if the line and plane are parallel
  27. if(dist1 == dist2) return null;//they are
  28.  
  29. //find the point of intersection
  30. point_intersect = origin.add((far_point.subtract(origin)).multiply((-dist1 / (dist2 - dist1))));
  31.  
  32. //test the point against all the edges of the triangle
  33. test_vector = normal.crossProduct((point_b.subtract(point_a)));
  34. if(test_vector.dotProduct(point_intersect.subtract(point_b)) < 0.0f)
  35. return null;//not inside face
  36.  
  37. test_vector = normal.crossProduct((point_c.subtract(point_b)));
  38. if(test_vector.dotProduct(point_intersect.subtract(point_c)) < 0.0f)
  39. return null;//not inside face
  40.  
  41. test_vector = normal.crossProduct((point_a.subtract(point_c)));
  42. if(test_vector.dotProduct(point_intersect.subtract(point_a)) < 0.0f)
  43. return null;//not inside face
  44.  
  45. //the point is inside the face
  46. return point_intersect;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement