Circle line-segment collision detection algorithm?

前端 未结 28 1764
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:38

I have a line from A to B and a circle positioned at C with the radius R.

\"Image\"

What is a good alg

28条回答
  •  轮回少年
    2020-11-22 07:02

    enter image description here

    ' VB.NET - Code
    
    Function CheckLineSegmentCircleIntersection(x1 As Double, y1 As Double, x2 As Double, y2 As Double, xc As Double, yc As Double, r As Double) As Boolean
        Static xd As Double = 0.0F
        Static yd As Double = 0.0F
        Static t As Double = 0.0F
        Static d As Double = 0.0F
        Static dx_2_1 As Double = 0.0F
        Static dy_2_1 As Double = 0.0F
    
        dx_2_1 = x2 - x1
        dy_2_1 = y2 - y1
    
        t = ((yc - y1) * dy_2_1 + (xc - x1) * dx_2_1) / (dy_2_1 * dy_2_1 + dx_2_1 * dx_2_1)
    
        If 0 <= t And t <= 1 Then
            xd = x1 + t * dx_2_1
            yd = y1 + t * dy_2_1
    
            d = Math.Sqrt((xd - xc) * (xd - xc) + (yd - yc) * (yd - yc))
            Return d <= r
        Else
            d = Math.Sqrt((xc - x1) * (xc - x1) + (yc - y1) * (yc - y1))
            If d <= r Then
                Return True
            Else
                d = Math.Sqrt((xc - x2) * (xc - x2) + (yc - y2) * (yc - y2))
                If d <= r Then
                    Return True
                Else
                    Return False
                End If
            End If
        End If
    End Function
    

提交回复
热议问题