This code will calculate whether or not a line will intersect with a triangle in 3D space, and store the intersection coordinates in ix#, iy#, iz# if made global.
Note that the vectors 1 and 2 have to be created in order to work.
The D3D plugin by Cloggy is only used for visualisation of the line. Leaving those commands out will not affect the function.
Language:
Dark Basic Pro
Code:
sync on : sync rate 0 D3D_init `Necessary to make the function work r = make vector3(1) r = make vector3(2) global ix#, iy#, iz# as float `Store values x1# = -5 : x2# = -5 : x3# = 2 y1# = -3 : y2# = 4 : y3# = 1 z1# = 2 : z2# = -4 : z3# = -1 ax# = 0 : bx# = 0 ay# = -2 : by# = 2 az# = 5 : bz# = -5 `Visualisation make object triangle 1, x1#, y1#, z1#, x2#, y2#, z2#, x3#, y3#, z3# make object cube 2, 0.5 do `Display screen fps text 5, 25, str$(screen fps()) `ang# = wrapvalue(ang# + 0.1) ang# = 45 position camera newxvalue(0, ang#, 15), 15, newzvalue(0, ang#, 15) point camera 0, 0, 0 D3D_line3D ax#, ay#, az#, bx#, by#, bz# by# = by# + (mousemovey()*0.1) bx# = bx# + (mousemovex()*0.1) text 5, 5, str$(CalcIntersection(x1#, y1#, z1#, x2#, y2#, z2#, x3#, y3#, z3#, ax#, ay#, az#, bx#, by#, bz#)) position object 2, ix#, iy#, iz# sync loop function CalcIntersection(x1#, y1#, z1#, x2#, y2#, z2#, x3#, y3#, z3#, ax#, ay#, az#, bx#, by#, bz#) `Reset result result = 0 dec x2#, x1# : dec y2#, y1# : dec z2#, z1# dec x3#, x1# : dec y3#, y1# : dec z3#, z1# dec ax#, x1# : dec ay#, y1# : dec az#, z1# dec bx#, x1# : dec by#, y1# : dec bz#, z1# `Calculate u, v and w u# = (y2#*z3#) - (z2#*y3#) v# = (z2#*x3#) - (x2#*z3#) w# = (x2#*y3#) - (y2#*x3#) `Calculate a,b,c a# = bx# - ax# b# = by# - ay# c# = bz# - az# n# = (u#*a# + v#*b# + w#*c#) if n# = 0.0 then exitfunction 0 k# = -(u#*ax# + v#*ay# + w#*az#) / n# if k# >= 0.0 and k# <= 1.0 then result = 1 `Calculate new x# = ax# + k#*a# y# = ay# + k#*b# z# = az# + k#*c# if result = 1 `Calculate angles set vector3 1, x2# - x#, y2# - y#, z2# - z# set vector3 2, x3# - x#, y3# - y#, z3# - z# t# = dot product vector3(1, 2) a1# = acos(t# / (length vector3(1)*length vector3(2))) set vector3 1, x3# - x#, y3# - y#, z3# - z# set vector3 2, -x#, -y#, -z# t# = dot product vector3(1, 2) a2# = acos(t# / (length vector3(1)*length vector3(2))) set vector3 1, -x#, -y#, -z# set vector3 2, x2# - x#, y2# - y#, z2# - z# t# = dot product vector3(1, 2) a3# = acos(t# / (length vector3(1)*length vector3(2))) a# = a1# + a2# + a3# if a# > 359.9 and a# < 360.1 `Get intersection ix# = x1# + x# iy# = y1# + y# iz# = z1# + z# else result = 0 endif endif endfunction result
No votes yet