Hello folks,

I was looking for solution about Ray triangle intersection and found some that have applied to my project.

I found that I can validate the line pass through with given codes but the coordinate of intersection point aren’t correct, that appears in wrong position.

Anyone can help me to check what is the problem in my program and fix its error?

```
struct Ray {
vec3 Origin;
vec3 Dir;
};
// Check whether the intersect point is in triangle
bool PointInOrOn(vec3 P1, vec3 P2, vec3 A, vec3 B) {
// if the line from a corner point to the intersection point is between the to legs which are connected to the corner point
vec3 CP1 = cross(B - A, P1 - A);
vec3 CP2 = cross(B - A, P2 - A);
// Return its result
return dot(CP1, CP2) >= 0;
}
// Check whether the point is in triangle
bool PointInTriangle(vec3 px, vec3 p1, vec3 p2, vec3 p3) {
return PointInOrOn(px, p1, p2, p3) && PointInOrOn(px, p2, p3, p1) && PointInOrOn(px, p3, p1, p2);
}
// Check intersection point
vec3 IntersectPlane(Ray ray, vec3 p1, vec3 p2, vec3 p3) {
// Direction
vec3 D = ray.Dir;
// The normal vector of the plane can be calculated by the cross product of 2 legs of the triangle
vec3 N = cross(p3 - p1, p2 - p1);
// The intersection point X
vec3 X = ray.Origin + D * dot(p1 - ray.Origin, N) / dot(D, N);
// Return coordinate of intersect point
return X;
}
// Check intersection between given line and triangle + obtain coordinate of intersect point
bool IntersectTriangle(Ray ray, vec3 p1, vec3 p2, vec3 p3, vec3 &X) {
// Get coordinate of intersect point
X = IntersectPlane(ray, p1, p2, p3);
// Check intersection
return PointInTriangle(X, p1, p2, p3);
}
// Main
int main() {
// Triangle
vec3 p1 = vec3(-0.5, 0.0, -1.5);
vec3 p2 = vec3(-2.5, 0.0, 1.0);
vec3 p3 = vec3(1.5, 0.0, 1.0);
// Line
Ray ray;
ray.Origin = vec3(1.0, 1.5, 0.0);
ray.Dir = vec3(-2.0, -1.5, 0.0);
// Intersection point
vec3 X = vec3(0.0, 0.0, 0.0);
// Intersection check + obtain coordinate of intersection point
bool rt = IntersectTriangle(ray, p1, p2, p3, X);
return 0;
}
```

Below is the result I get when I draw intersection point between Origin and Dir.

What I want to have is something similar to below