arkamedus Posted December 11, 2014 Share Posted December 11, 2014 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 intersectionArguments{ 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 vectorsfunction vecDist(a, { return Math.sqrt( Math.pow( (a[0] - b[0]) ,2)+Math.pow( (a[1] - b[1]) ,2)+Math.pow( (a[2] - b[2]),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[1] - z[1]) * (n[2] - z[2]) - (n[1] - z[1]) * (r[2] - z[2]), i = (r[2] - z[2]) * (n[0] - z[0]) - (n[2] - z[2]) * (r[0] - z[0]), t = (r[0] - z[0]) * (n[1] - z[1]) - (n[0] - z[0]) * (r[1] - z[1]), e = Math.sign(a * (z[0] - y[0]) + i * (z[1] - y[1]) + t * (z[2] - y[2])), u = x[0] * a + x[1] * i + x[2] * t; if (e != Math.sign(u) || 0 == e) return false; var v = (a * z[0] + i * z[1] + t * z[2] - (a * y[0] + i * y[1] + t * y[2])) / u, f = x[0] * v + y[0], g = x[1] * v + y[1], s = x[2] * v + y[2], c = (z[1] - g) * (r[2] - s) - (r[1] - g) * (z[2] - s), h = (z[2] - s) * (r[0] - f) - (r[2] - s) * (z[0] - f), M = (z[0] - f) * (r[1] - g) - (r[0] - f) * (z[1] - g); if (0 > c * a + h * i + M * t) return false; var c = (r[1] - g) * (n[2] - s) - (n[1] - g) * (r[2] - s), h = (r[2] - s) * (n[0] - f) - (n[2] - s) * (r[0] - f), M = (r[0] - f) * (n[1] - g) - (n[0] - f) * (r[1] - g); if (0 > c * a + h * i + M * t) return false; var c = (n[1] - g) * (z[2] - s) - (z[1] - g) * (n[2] - s), h = (n[2] - s) * (z[0] - f) - (z[2] - s) * (n[0] - f), M = (n[0] - f) * (z[1] - g) - (z[0] - f) * (n[1] - 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.