# Ray-Triangle Intersection Detection using Barycentric Coordinates

I am attempting to convert the algorithm from http://www.cbloom.com/3d/techdocs/fast_ray_tri.txt to java code, but my solution does not function correctly.

The only intentional change I made was for the second point, my method accepts a unit vector instead of the other end of the line segment.

For now, all collision calculations are done in this one method (nothing is pre-calculated).

Any suggestions as to what I may have done wrong?

//collision with barycentric coordinates
boolean checkCollision(Vector3f rayStart, Vector3f rayDirection){

Vector3f normal=new Vector3f().cross(new Vector3f(point1).sub(point0), new Vector3f(point2).sub(point0)).normalize();

planeOffset=-normal.dot(point0);

Vector3f
edge1 = new Vector3f(point1).sub(point0),
edge2 = new Vector3f(point2).sub(point1),
edgePerp1 = new Vector3f().cross(normal, edge1),
edgePerp2 = new Vector3f().cross(normal, edge2);

float edgePlaneDist1 = edgePerp1.dot(point0),
edgePlaneDist2 = edgePerp2.dot(point1);

{
float distance1=edgePerp1.dot(point2)-edgePlaneDist1;
float distance2=edgePerp2.dot(point0)-edgePlaneDist2;

edgePlaneDist1/=distance1;
edgePlaneDist2/=distance2;

edgePerp1.scale(1/distance1);
edgePerp2.scale(1/distance2);
}

//point-plane distance
float dFm=normal.dot(rayStart)-planeOffset;

Vector3f rayEnd=new Vector3f(rayStart).add(new Vector3f(rayDirection).scale(30));

float dTo=normal.dot(rayEnd)-planeOffset;

float denom=dTo-dFm;

float uTimesDenom = edgePerp1.dot(temp) - edgePlaneDist1 * denom;

if ( uTimesDenom < 0 || uTimesDenom > denom )
{
// off triangle
return false;
}

float vTimesDenom = edgePerp2.dot(temp) - edgePlaneDist2 * denom;

if ( vTimesDenom < 0 || (uTimesDenom+vTimesDenom) > denom )
{
// off triangle
return false;
}

return true;

• it's hard to spot out of the first look the problem here , so it would really help if you can simplify the code and provide input data that is mathematically correct but the code fails to compute. – Raxvan Jul 30 '14 at 7:45
• I don't have time to debug your code, but this is something that is commonly done by many people. Perhaps you can take a look at some reference code someone else has written, and then double check your math? Many people learn this from Ericson's book Real-Time Collision Detection. – RandyGaul Jul 30 '14 at 20:49