Code archives/Algorithms/Is In Triangle 2D

This code has not been declared by its author to be Public Domain code, and therefore should not be assumed to be so.

Download source code

Is In Triangle 2D by Peter Scheutz
(Posted 24 years ago)
Check if point is inside triangle
; by Charles H. Giffen from
; http://groups.google.com/groups?selm=3784B03B.F1CCF05D%40virginia.edu&oe=UTF-8&output=gplain
; Blitz Port by Peter Scheutz

Function IsInTriangle ( px#,py#, ax#,ay#,bx#,by#,cx#,cy# ) 

	Local bc#,ca#,ab#,ap#,bp#,cp#,abc#

	bc# = bx*cy - by*cx 
	ca# = cx*ay - cy*ax 
	ab# = ax*by - ay*bx
	ap# = ax*py - ay*px
	bp# = bx*py - by*px
	cp# = cx*py - cy*px
	abc# = Sgn(bc + ca + ab)

	If (abc*(bc-bp+cp)>0) And (abc*(ca-cp+ap)>0) And (abc*(ab-ap+bp)>0) Then Return True
End Function

Comments

Peter Scheutz
(Posted 23 years ago)
Here is an example.

Graphics 800,600,0,2


x1#=50
y1#=50

x2#=150
y2#=50


x3#=70
y3#=350



SetBuffer BackBuffer()

Color 255,255,255

While Not KeyHit(1)
	
	Cls
	
	Line x1,y1,x2,y2
	Line x3,y3,x2,y2
	Line x1,y1,x3,y3
	
	x#=MouseX()
	y#=MouseY()
	
	
	If IsInTriangle(x,y,x1,y1,x2,y2,x3,y3)
		
		Text 10,10,"Inside"
		
	Else
		
		Text 10,10,"-"
		
	EndIf
	
	
	
	Flip
	
Wend


End


; by Charles H. Giffen from
; <a href="http://groups.google.com/groups?selm=3784B03B.F1CCF05D%40virginia.edu&oe=UTF-8&output=gplain" target="_blank">http://groups.google.com/groups?selm=3784B03B.F1CCF05D%40virginia.edu&oe=UTF-8&output=gplain</a>
; Blitz Port by Peter Scheutz

Function IsInTriangle ( px#,py#, ax#,ay#,bx#,by#,cx#,cy# ) 

	Local bc#,ca#,ab#,ap#,bp#,cp#,abc#

	bc# = bx*cy - by*cx 
	ca# = cx*ay - cy*ax 
	ab# = ax*by - ay*bx
	ap# = ax*py - ay*px
	bp# = bx*py - by*px
	cp# = cx*py - cy*px
	abc# = Sgn(bc + ca + ab)

	If (abc*(bc-bp+cp)>0) And (abc*(ca-cp+ap)>0) And (abc*(ab-ap+bp)>0) Then Return True
End Function


Code Archives Forum