Code archives/3D Graphics - Maths/Circle Circle Instersection Points

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

Download source code

Circle Circle Instersection Points by Haramanai2005
It's not my code and it's just a translation of a java code in BlitzMax
All credits go here

Circle Intersection
By William Ngan (http:/www.metaphorical.net)
Processing BETA code (http://www.processing.org)
Rem 
 	Circle Intersection
	 By William Ngan (http:/www.metaphorical.net)
	 Processing BETA code (http://www.processing.org)
End Rem

Type Circle 

	Field x, y, r, r2

	Function create:Circle( px#, py#, pr# ) 
		Local Circle_:Circle = New Circle
		Circle_.x = px
		Circle_.y = py
		Circle_.r = pr
		Circle_.r2 = pr*pr
		Return Circle_
	End Function

End Type


Function intersect( cA:Circle , cB:Circle ) 

	Local dx# = cA.x - cB.x
	Local  dy# = cA.y - cB.y
	Local  d2# = dx*dx + dy*dy
	Local  d# = Sqr( d2 )

	If  d>cA.r+cB.r Or d<Abs(cA.r-cB.r) Return'; // no solution
	

	Local a# = (cA.r2 - cB.r2 + d2) / (2*d)
	Local h# = Sqr( cA.r2 - a*a )
	Local x2# = cA.x + a*(cB.x - cA.x)/d
	Local y2# = cA.y + a*(cB.y - cA.y)/d


	DrawRect( x2, y2, 5, 5 )

	Local paX% =  x2 + h*(cB.y - cA.y)/d 
	Local paY% =  y2 - h*(cB.x - cA.x)/d 
	Local pbX# = x2 - h*(cB.y - cA.y)/d
	Local pbY# = y2 + h*(cB.x - cA.x)/d
	DrawText pax , 10 , 10
	DrawRect paX , PaY , 5 , 5
	DrawRect pbX , PbY , 5 , 5

End Function

Function DrawCircle(R:Circle)
	DrawOval R.x - R.r  , R.y - R.r , R.r*2 , R.r*2
End Function

Local Cir:Circle = Circle.create(10 , 10 , 100)
Local Cir2:Circle = Circle.create(100 , 100 , 50)

Graphics 640 , 480 , 0

While Not KeyDown(Key_Escape)
	Cls
	SetColor 255 , 0 , 0
	drawCircle(Cir)
	SetColor 0 , 255 , 0
	drawCircle(Cir2)
	SetColor 0 , 0 , 255
	intersect(cir , cir2)
	Cir.X = MouseX()
	Cir.Y = MouseY()
	Flip
	FlushMem
Wend

Comments

Haramanai2005
And just a function

Function Circle_Circle_intersect(paX# Var , paY# Var , pbX# Var , pbY# Var , x1# , y1# , r1# , x2# , y2# , r2#) 


	Local dx# = x1 - x2
	Local  dy# = y1 - y2
	Local  d2# = dx*dx + dy*dy
	Local  d# = Sqr( d2 )

	If  d>r1+r2 Or d<Abs(r1-r2) Then Return False'; // no solution
	

		Local a# = (r1*r1 - r2*r2 + d2) / (2*d)
		Local h# = Sqr( r1*r1 - a*a )
		Local rx2# = x1 + a*(x2 - x1)/d
		Local ry2# = y1 + a*(y2 - y1)/d


		paX# =  rx2 + h*(y2 - y1)/d 
		paY# =  ry2 - h*(x2 - x1)/d 
		pbX# = rx2 - h*(y2 - y1)/d
		pbY# = ry2 + h*(x2 - x1)/d

		Return True
	
End Function



Bobysait2008
we maybe could optimise using simple previous test:
Function intersect( cA:Circle , cB:Circle ) 
	Local R0:Float=cA.r+cB.r
	Local dx:Float=cA.x - cB.x
	' no solution ------------------
		If Abs(dx)>R0 Return False
		Local dy:Float=cA.y - cB.y
		If Abs(dy)>R0 Return False
		Local  d2# = dx*dx + dy*dy
		If d2>R0*R0 Return False
		Local R_:Float=cA.r-cB.r
		If d2<R_*R_ Return False
	' ------------------------------
	Local  d# = Sqr( d2 )
	[...]
End Function



Code Archives Forum