Rectangle.IntersetsWith() returning true whenever the two rectangles are on the same X axis

女生的网名这么多〃 提交于 2020-01-16 13:27:34

问题


I'm trying to recreate Battleship and I'm using Rectangle.IntersectsWith() to find collisions between each ship. Whenever I put the ships on the same x axis on the grid, the function returns true. It doesn't if they are on the same y axis or if they are touching.

This is the code I use to test every ship against every other ship (If you know of an easier way, I'd love to hear about it).

Public Sub CheckForCollision()
    Dim ships As Ship() = _
        {AirCraftCarrier, Battleship, Submarine, _
            Destroyer, PatrolBoat}

    For i As Integer = 0 To 4
        Dim ship1 As Ship = ships(i)
        For j As Integer = 0 To 4
            Dim ship2 As Ship = ships(j)
            If ship1.name <> ship2.name Then
                If ship1.rect.IntersectsWith(ship2.rect) Then
                    Debug.Print(ship1.name & " and " & ship2.name & " intersect")
                End If

            End If
        Next
    Next
End Sub

The rects x and y values are changed whenever the ship is moved to a new spot. I just set it to PictureBox location.


回答1:


Testing for a collison on a specific ship:

Public Function SoundCollision(thisShip As Ship) as Boolean
    Dim ships As Ship() = _
        {AirCraftCarrier, Battleship, Submarine, _
            Destroyer, PatrolBoat}

    Dim bRet as Boolean = False          ' assume not

    For n As Integer = 0 To 4
        If ships(n).Name <> thisShip.Name Then
            If thisShip.rect.IntersectsWith(ships(n).rect) Then
                bret = true
                Debug.Print(ships(n).name & " intersects " & thisShip.name)
                Exit For            ' skip the rest
            End If

        End If
    Next
    Return bRet
End Sub

If it is method in your Ship class, use Me instead of thisShip and dont pass it



来源:https://stackoverflow.com/questions/23665519/rectangle-intersetswith-returning-true-whenever-the-two-rectangles-are-on-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!