Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Find the points where a line intersects a circle This example shows how to find the points where a line intersects a circle in Visual Basic 6. graphics, line, circle, intersection Graphics, Algorithms

The FindLineCircleIntersections function calculates the points of intersection between a line and a circle. It takes as parameters a circle's center point and radius, and two points on the line. It uses ByRef parameters to return the coordinates of the points of intersection. The function returns the number of points of intersection (0, 1, or 2).

To fund the points of intersection, the code considers the line as generated by the equations:

```    X(t) = x1 + (x2 - x1) * t
Y(t) = y1 + (y2 - y1) * t```

Where t ranges from 0 to 1 to draw the line segment.

The code plugs these equations into the equation for a circle:

`    (X - Cx)^2 + (Y - Cy)^2 = radius^2`

It then solves for t by using the quadratic formula. The result is 0, 1, or 2 values for t. It plugs those values back into the equations for the line to get the points of intersection.

```Private Function FindLineCircleIntersections(ByVal cx As _
Single, ByVal cy As Single,
ByVal radius As Single, ByVal x1 As Single, ByVal y1 As _
Single, ByVal x2 As Single,
ByVal y2 As Single, ByRef ix1 As Single, ByRef iy1 As _
Single, ByRef ix2 As Single,
ByRef iy2 As Single) As Integer
Dim dx As Single
Dim dy As Single
Dim A As Single
Dim B As Single
Dim C As Single
Dim det As Single
Dim t As Single

dx = x2 - x1
dy = y2 - y1

A = dx * dx + dy * dy
B = 2 * (dx * (x1 - cx) + dy * (y1 - cy))
C = (x1 - cx) * (x1 - cx) + (y1 - cy) * (y1 - cy) - _

det = B * B - 4 * A * C
If (A <= 0.0000001) Or (det < 0) Then
' No real solutions.
FindLineCircleIntersections = 0
ElseIf det = 0 Then
' One solution.
FindLineCircleIntersections = 1
t = -B / (2 * A)
ix1 = x1 + t * dx
iy1 = y1 + t * dy
Else
' Two solutions.
FindLineCircleIntersections = 2
t = (-B + Sqr(det)) / (2 * A)
ix1 = x1 + t * dx
iy1 = y1 + t * dy
t = (-B - Sqr(det)) / (2 * A)
ix2 = x1 + t * dx
iy2 = y1 + t * dy
End If
End Function```

If you need to know, a point of intersection lies on the line segment if 0 <= t <= 1 and on an extension of the segment otherwise.