カテゴリー
Visual Basic

ボールとブロックの当たり判定

タイマーイベント内に、ボールとブロックの当たり判定を追加します。

しかし、ブロックは複数あってループで当たり判定を行う必要があります。

タイマーイベント内の処理が長くなるとコードが読みにくくなるので、HitBricksというサブプロシージャを作って、その中でブロックとボールの当たり判定を行うようにしましょう。

ついでに、ボールと壁の当たり判定は HitWall、ラケットとボールの当たり判定はHitRacketというサブプロシージャに分割します。

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        HitWall()
        HitRacket()
        HitBricks()

        x = x + dx
        y = y + dy
        Ball.Left = x
        Ball.Top = y
    End Sub

    Public Sub HitWall()
        If x + dx <= 0 Or x + Ball.Width + dx > ClientSize.Width Then
            dx = -dx
        End If
        If y + dy <= 0 Or y + Ball.Height + dy > ClientSize.Height Then
            dy = -dy
        End If
    End Sub

    Public Sub HitRacket()
        Dim br, rr As Rectangle
        br = New Rectangle(x, y, Ball.Width, Ball.Height)
        rr = New Rectangle(Racket.Left, Racket.Top, Racket.Width, Racket.Height)
        If rr.IntersectsWith(br) And dy > 0 Then
            dy = -dy
        End If
    End Sub

    Public Sub HitBricks()
        Dim i, j As Integer
        Dim r, br As Rectangle
        Dim b As Label

        br = New Rectangle(x, y, Ball.Width, Ball.Height)
        For i = 0 To 9
            For j = 0 To 5
                b = brick(i, j)
                r = New Rectangle(b.Left, b.Top, b.Width, b.Height)
                If b.Visible = True And r.IntersectsWith(br) Then
                    dy = -dy
                    b.Visible = False
                    Exit Sub
                End If
            Next
        Next
    End Sub

ボールがブロックに当たると、ブロックが消えるようになりました。