In the previous article, we only described how to judge whether a ray intersects a triangle, but we missed an important information, that is, the distance between the ray and the point where the triangle intersects. This distance is very important because we need to know which object is closest to the origin of the ray when a ray passes through multiple objects

The construction of parametric equations

Construct the parametric equation of the ray. The first point of the ray can be expressed as


P = O + t R P=O+tR

P is the point of intersection with the triangle, O is the origin of the ray, R is the direction, and T is the distance from the ray to the intersection of the triangle

Parametric equation construction of plane


A x + B y + C z + D = 0 Ax+By+Cz+D=0

The simultaneous equations are solved


t = ( A O x + B O y + C O z + D ) / ( A R x + B R y + C R z ) t=-(A*O_x+B*O_y+C*O_z+D)/(A*R_x+B*R_y+C*R_z )

reduction


t = ( N ( A . B . C ) O + D ) / ( N ( A . B . C ) R ) t=-(N(A,B,C)*O+D)/(N(A,B,C)*R)

That gives you the distance t, and you plug it into the ray parametric equation and you get the point of intersection

Validity judgment of intersection points

The general equation of the plane mentioned above only explains the plane where the triangle lies. After we obtain the intersection points of the ray and the plane, we need to further determine whether the intersection points are in the triangle. The calculation and principle of the judgment can be viewed in the previous article, and there will be no more talk here