Cormack Cormack - 6 months ago 26
Vb.net Question

How to make an IF statement work inside a KeyDown PrivateSub

I am programming a basic pong game in visual basic and need help with an if statement. When the ball hits an edge it resets to the middle of the screen, and "resetBall" gets set to true, which in turn should allow me to press "R" and make it move again.

Private Sub Timer1_Tick(sender As Object, e As KeyEventArgs) Handles Timer1.Tick

If PictureBox3.Bounds.IntersectsWith(PictureBox2.Bounds) Then
direction = 1
End If

If PictureBox3.Bounds.IntersectsWith(PictureBox1.Bounds) Then
direction = 0
End If

If direction = 0 Then
PictureBox3.Left += 15
End If

If direction = 1 Then
PictureBox3.Left -= 15
End If

If PictureBox3.Bounds.IntersectsWith(leftBumper.Bounds) Then
PictureBox3.SetBounds(325, 165, 0, 0, BoundsSpecified.X Or BoundsSpecified.Y)
direction = 2
resetBall0 = True
End If

If PictureBox3.Bounds.IntersectsWith(rightBumper.Bounds) Then
PictureBox3.SetBounds(325, 165, 0, 0, BoundsSpecified.X Or BoundsSpecified.Y)
direction = 2
resetBall1 = True
End If

End Sub


But when I use an "If" statement in the next part of the code, it doesn't work.

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

Select Case e.KeyCode

Case Keys.W
PictureBox1.Top -= 8

Case Keys.S
PictureBox1.Top += 8

Case Keys.Up
PictureBox2.Top -= 8

Case Keys.Down
PictureBox2.Top += 8

If resetBall1 = True Then
Select Case e.KeyCode
Case Keys.R
direction = 1
End Select
End If

If resetBall0 = True Then
Select Case e.KeyCode
Case Keys.R
direction = 0
End Select
End If

End Select
End Sub

Answer Source

You're inside Case Keys.Down so Keycode will never be R...it's Down. Move your logic to its own case statement:

    Select Case e.KeyCode    
        Case Keys.W
            PictureBox1.Top -= 8

        Case Keys.S
            PictureBox1.Top += 8

        Case Keys.Up
            PictureBox2.Top -= 8

        Case Keys.Down
            PictureBox2.Top += 8

       Case Keys.R
            If resetBall1 = True Then
                direction = 1
            End If

            If resetBall0 = True Then
                direction = 0
            End If
    End Select
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download