Code archives/Graphics/Line Overlap Circle

This code has been declared by its author to be Public Domain code.

Download source code

Line Overlap Circle by nawi
(Posted 22 years ago)
Check if line is overlapping circle. Code translated from google to BlitzBasic by Nawi and touched by Beaker.
Function LineOverlapCircle(x1#,y1#,x2#,y2#,cx#,cy#,Radius#)
	;'Calc Closest Point To circle center
	Local dx31#=cx#-x1#
	Local dx21#=x2#-x1#
	Local dy31#=cy#-y1#
	Local dy21#=y2#-y1#
	Local d#=((dx21#*dx21#)+(dy21#*dy21#))
	If d#<>0 Then d#=((dx31#*dx21#)+(dy31#*dy21#))/d#
	;'Clip To the line segments legal bounds
	If d#<0.0 Then d#=0
	If d#>1.0 Then d#=1
	Local dx#=cx#-(x1#+(dx21#*d#))
	Local dy#=cy#-(y1#+(dy21#*d#))
	If Radius# => Sqr((dx#*dx#)+(dy#*dy#))
		;'Line intersects circle
		Return 1 
	EndIf
	Return 0
End Function

Comments

Pongo
(Posted 22 years ago)
very slight optimization,... since you don't need to know the actual distance, just check it you can avoid using Sqr

change this line:
If Radius# => Sqr((dx#*dx#)+(dy#*dy#))

to this:
If Radius# * Radius# => (dx#*dx#)+(dy#*dy#)

in my quick tests it came out slightly faster, and I don't think I broke the function.

Code Archives Forum