# 3D Ray-Triangle Intersection

## Recommended Posts

Here is a simple solution for determining the position and distance of a ray triangle intersection.

rayTriangle(from [x,y,z], normal [x,y,z], vertex1 [x,y,z], vertex2 [x,y,z], vertex3 [x,y,z]) ; Returns the position of the intersection and the distance to that point as an array [x, y, z, distance], returns false if no intersection
Arguments{  from: starting position of the ray, normal: directional vector of the ray, vertex1,2,3: vertices of the triangle }

vecDist( vector1 [x,y,z], vector2 [x,y,z] ) ; Returns distance between two vectors

`function vecDist(a, {    return Math.sqrt( Math.pow( (a - b)  ,2)+Math.pow( (a - b)  ,2)+Math.pow( (a - b),2) );}`
`function rayTriangle(y, x, z, r, n) { // rayTriangle(from [x,y,z], normal [x,y,z], vertex1 [x,y,z], vertex2 [x,y,z], vertex3 [x,y,z])    var a = (r - z) * (n - z) - (n - z) * (r - z),        i = (r - z) * (n - z) - (n - z) * (r - z),        t = (r - z) * (n - z) - (n - z) * (r - z),        e = Math.sign(a * (z - y) + i * (z - y) + t * (z - y)),        u = x * a + x * i + x * t;    if (e != Math.sign(u) || 0 == e) return false;    var v = (a * z + i * z + t * z - (a * y + i * y + t * y)) / u,        f = x * v + y,        g = x * v + y,        s = x * v + y,        c = (z - g) * (r - s) - (r - g) * (z - s),        h = (z - s) * (r - f) - (r - s) * (z - f),        M = (z - f) * (r - g) - (r - f) * (z - g);    if (0 > c * a + h * i + M * t) return false;    var c = (r - g) * (n - s) - (n - g) * (r - s),        h = (r - s) * (n - f) - (n - s) * (r - f),        M = (r - f) * (n - g) - (n - f) * (r - g);    if (0 > c * a + h * i + M * t) return false;    var c = (n - g) * (z - s) - (z - g) * (n - s),        h = (n - s) * (z - f) - (z - s) * (n - f),        M = (n - f) * (z - g) - (z - f) * (n - g);    return 0 > c * a + h * i + M * t ? false : [f, g, s, vecDist(y, [f, g, s])];}`

I am by no means a professional, and there are probably way better ways to do this, including firstly, using a framework. In my case, I am developing my own framework and needed a simple solution.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.