Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Precision collision detection between a ray and a triangle.
- * @param origin - origin of the picking ray
- * @param far_point - far collision of the picking ray
- * @param point_a - the triangle's vertex0
- * @param point_b - the triangle's vertex1
- * @param point_c - the triangle's vertex2
- * @return - the location of the intersection, as Vector3, else null for no collision
- */
- public static Vector3 rayTriangleIntersect(Vector3 origin, Vector3 far_point, Vector3 point_a, Vector3 point_b, Vector3 point_c)
- {
- Vector3 normal, point_intersect, test_vector;
- //find the triangles normal
- normal = (point_b.subtract(point_a).normalize().crossProduct((point_c.subtract(point_a).normalize())));
- //find the distance from origin to the triangle
- float dist1 = (origin.subtract(point_a).dotProduct(normal));
- //find the distance from far_point to the triangle
- float dist2 = (far_point.subtract(point_a).dotProduct(normal));
- //check to see if the ray intersects the triangle
- if((dist1 * dist2) >= 0.0f) return null;//it doesn't
- //check if the line and plane are parallel
- if(dist1 == dist2) return null;//they are
- //find the point of intersection
- point_intersect = origin.add((far_point.subtract(origin)).multiply((-dist1 / (dist2 - dist1))));
- //test the point against all the edges of the triangle
- test_vector = normal.crossProduct((point_b.subtract(point_a)));
- if(test_vector.dotProduct(point_intersect.subtract(point_b)) < 0.0f)
- return null;//not inside face
- test_vector = normal.crossProduct((point_c.subtract(point_b)));
- if(test_vector.dotProduct(point_intersect.subtract(point_c)) < 0.0f)
- return null;//not inside face
- test_vector = normal.crossProduct((point_a.subtract(point_c)));
- if(test_vector.dotProduct(point_intersect.subtract(point_a)) < 0.0f)
- return null;//not inside face
- //the point is inside the face
- return point_intersect;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement