VB.NET Liang-Barsky实现的麻烦

时间:2010-11-06 16:35:48

标签: vb.net 2d collision-detection line-segment

经过一番研究,我决定在我的2D游戏中使用 Liang-Barsky 线裁剪算法。谷歌没有提供这种算法的任何VB.NET实现,但提供了大量的C / ++。因此,正如我在C ++中的知识,决定port one found on Skytopia到VB.Net。不幸的是,它不适用于:

Public Class PhysicsObject
    Public Function CollideRay(ByVal p0 As Point, ByVal p1 As Point, ByRef clip0 As Point, ByRef clip1 As Point) As Boolean
        Dim t0 As Double = 0.0
        Dim t1 As Double = 1.0
        Dim xdelta As Double = p1.X - p0.X
        Dim ydelta As Double = p1.Y - p0.Y
        Dim p, q, r As Double

        For edge = 0 To 3
            ' Traverse through left, right, bottom, top edges
            If (edge = 0) Then
                p = -xdelta
                q = -(AABB.Left - p0.X)
            ElseIf (edge = 1) Then
                p = xdelta
                q = (AABB.Right - p0.X)
            ElseIf (edge = 2) Then
                p = -ydelta
                q = -(AABB.Bottom - p0.Y)
            ElseIf (edge = 3) Then
                p = ydelta
                q = (AABB.Top - p0.Y)
            End If

            r = q / p

            If p = 0 And q < 0 Then Return False ' Don't draw line at all. (parallel line outside)

            If p < 0 Then
                If r > t1 Then
                    Return False ' Don't draw line at all.
                ElseIf r > t0 Then
                    t0 = r ' Line is clipped!
                End If
            ElseIf p > 0 Then
                If r < t0 Then
                    Return False ' Don't draw line at all.
                ElseIf r < t1 Then
                    t1 = r ' Line is clipped!
                End If
            End If
        Next

        clip0.X = p0.X + t0 * xdelta
        clip0.Y = p0.Y + t0 * ydelta
        clip1.X = p0.X + t1 * xdelta
        clip1.Y = p0.Y + t1 * ydelta

        Return True        ' (clipped) line is drawn
    End Function

    Public AABB As Rectangle
End Class

我正在使用类/方法:

    Dim testPhysics As PhysicsObject = New PhysicsObject
    testPhysics.AABB = New Rectangle(30, 30, 20, 20)

    Dim p0, p1 As Point
    p0 = New Point(0, 0)
    p1 = New Point(120, 120)

    Dim clip0, clip1 As Point
    clip0 = New Point(-1, -1)
    clip1 = New Point(-1, -1)

    GlobalRenderer.Graphics.DrawLine(Pens.LimeGreen, p0, p1)

    If testPhysics.CollideRay(p0, p1, clip0, clip1) Then
        GlobalRenderer.Graphics.DrawLine(Pens.Magenta, clip0, clip1)
    End If

然而, CollideRay 方法在其第3次边缘迭代(边缘= 3)时失败,r&lt; t0,因此函数返回false。

我想知道是否有人能够发现我的 CollideRay 函数的一些问题会导致这种行为,因为我很好并且真的很难过。

提前致谢。

1 个答案:

答案 0 :(得分:2)

代码假设一个不同的坐标系,请注意topEdge比链接网页中的bottomEdge 更大。您的测试适用于普通图形坐标,其中Bottom大于Top。你必须交换底部和顶部参数。