Line Intersect Triangle

Started by kevin, March 19, 2025, 11:59:51 AM

Previous topic - Next topic

kevin

Line Intersect Triangle


  The demo shows a line and spinning triangle.  You can position the line head / tail by holding the left or right mouse buttons down


PlayBASIC Code: [Select]
        openscreen 1000,950,32,true
// Mouse buttons to position the head / tail of the test line
// Space key to end

Type tTriangle
X1#,Y1#
X2#,Y2#
X3#,Y3#
EndType

dim poly as tTriangle pointer
poly = new tTriangle

Size# =500
Angle#=0
poly.x1 = GetScreenWidth()/2
poly.y1 = GetScreenHeight()/2

x1# = 100
y1# = 100

x2# = 700
y2# = 500

Setfps 61.7

do
cls

angle#=wrapangle(angle#,0.2)

if LeftKey() then angle#=wrapangle(angle#-1)
if RightKey() then angle#=wrapangle(angle#+1)

poly.x2 = poly.x1 +cos(angle#-35)*Size#
poly.y2 = poly.y1 +sin(angle#-35)*Size#
poly.x3 = poly.x1 +cos(angle#+35)*Size#
poly.y3 = poly.y1 +sin(angle#+35)*Size#

if leftmousebutton()
x1#=mousex()
y1#=mousey()
endif

if rightmousebutton()
x2#=mousex()
y2#=mousey()
endif

DrawPolygon(Poly,$334455)

State=LineIntersectTriangle(x1#,y1#,x2#,y2#, poly)

ThisRGB = -1
if State=0 then ThisRGB = $ff0000
linec x1#,y1#,x2#,y2#,ThisRGB

ink ThisRGB
print "Line Intersect Triangle:"+str$(State)
ink -1

Sync
loop spacekey()


end



psub Cross(x1#,y1#,x2#,y2#,x3#,y3#)
result=(((x2#-x1#)*(y3#-y1#))-((x3#-x1#)*(y2#-y1#)))
endpsub result




psub DrawPolygon(Poly as tTriangle pointer,ThisRGB)
tric Poly.X1#,Poly.Y1,Poly.X2#,Poly.Y2#,Poly.X3#,Poly.Y3#, ThisRGB
EndPsub



function LineIntersectTriangle(lx1#,ly1#,lx2#,ly2#, poly as tTriangle pointer)

px1#=poly.x1#
py1#=poly.y1#
px2#=poly.x2#
py2#=poly.y2#
px3#=poly.x3#
py3#=poly.y3#

// test #1 of vertex is clock wise (outside)
P1 = (Cross(lx1#,ly1#,px1#,py1#,px2#,py2#)>0) * 4
P1+= (Cross(lx1#,ly1#,px2#,py2#,px3#,py3#)>0) * 2
P1+= (Cross(lx1#,ly1#,px3#,py3#,px1#,py1#)>0)
if p1=%111 then ExitFunction true

P2 = (Cross(lx2#,ly2#,px1#,py1#,px2#,py2#)>0) * 4
P2+= (Cross(lx2#,ly2#,px2#,py2#,px3#,py3#)>0) * 2
P2+= (Cross(lx2#,ly2#,px3#,py3#,px1#,py1#)>0)
if p2=%111 then ExitFunction true

if LinesIntersect(lx1#,ly1#,lx2#,ly2#,px1#,py1#,px2#,py2#) then ExitFunction true
if LinesIntersect(lx1#,ly1#,lx2#,ly2#,px2#,py2#,px3#,py3#) then ExitFunction true
State=LinesIntersect(lx1#,ly1#,lx2#,ly2#,px3#,py3#,px1#,py1#)

EndFunction State







  More reading:

    - Lines Intersect

    - 2D portal rendering