Check for collision of two circles, get intersection points


Read comments in code for description.
For usage example see Triangulation Program problem, Reply #22

'required global variables (intersection coordinates to be returned):
Global xi1, yi1, xi2, yi2 'the intersection coords returned by c2cIntersect() function
 
'-----------------------------
' your code goes here
'-----------------------------
 
'=================================================
' Source: http://paulbourke.net/geometry/2circle/
' C source code example by Tim Voght
 
' Ported to JustBASIC
' by Andy Amaya
'=================================================
Function c2cIntersect(x0, y0, r0, x1, y1, r1)
    ' This function checks for the intersection of two circles.
    ' If one circle is wholly contained within the other a -1 is returned
    ' If there is no intersection of the two circles a 0 is returned
    ' If the circles intersect a 1 is returned and
    ' the coordinates are placed in xi1, yi1, xi2, yi2
 
    ' dx and dy are the vertical And horizontal distances between
    ' the circle centers.
    dx = x1 - x0
    dy = y1 - y0
 
    ' Determine the straight-Line distance between the centers.
    d = Sqr((dy*dy) + (dx*dx))
 
 
    ' Check for solvability.
    If (d > (r0 + r1)) Then
        'no solution. circles do Not intersect
        c2cIntersect = 0'
    End If
 
    If (d < Abs(r0 - r1)) Then
    ' no solution. one circle is contained in the other
        c2cIntersect = -1
    End If
 
    ' 'point 2' is the point where the Line through the circle
    ' intersection points crosses the Line between the circle
    ' centers.
 
    ' Determine the distance from point 0 To point 2.
    a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d)
 
    ' Determine the coordinates of point 2.
    x2 = x0 + (dx * a/d)
    y2 = y0 + (dy * a/d)
 
    ' Determine the distance from point 2 To either of the
    ' intersection points.
    h = Sqr((r0*r0) - (a*a))
 
    ' Now determine the offsets of the intersection points from
    ' point 2.
    rx = (0-dy) * (h/d)
    ry = dx * (h/d)
 
    ' Determine the absolute intersection points.
    xi1 = x2 + rx
    xi2 = x2 - rx
    yi1 = y2 + ry
    yi2 = y2 - ry
 
     c2cIntersect = 1
End Function