conquistador
conquistador

Reputation: 693

VB.NET Moving Objects Diagonally using Keys

How can I Move objects diagonally when two directional keys are pressed? How to do that? I tried adding elseif statement for Handling Up and Right together but It still move up or right when i press them together

  Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.Right Then
        Label1.Location = New Point(Label1.Location.X + 5, Label1.Location.Y)

    ElseIf e.KeyCode = Keys.Left Then
        Label1.Location = New Point(Label1.Location.X - 5, Label1.Location.Y)

    ElseIf e.KeyCode = Keys.Down Then
        Label1.Location = New Point(Label1.Location.X, Label1.Location.Y + 5)

    ElseIf e.KeyCode = Keys.Up Then
        Label1.Location = New Point(Label1.Location.X, Label1.Location.Y - 5)

    ElseIf e.KeyCode = Keys.Up And e.KeyCode = Keys.Right Then
        Label1.Location = New Point(Label1.Location.X + 5, Label1.Location.Y + 5)
    End If

    CheckIntersections()
    If Label1.Location.Y < 0 Then
        Label1.Location = New Point(Label1.Location.X, Me.Height)
    ElseIf Label1.Location.Y > Me.Height Then
        Label1.Location = New Point(Label1.Location.X, Me.Bottom = 0)
    ElseIf Label1.Location.X < 0 Then
        Label1.Location = New Point(Me.Width, Label1.Location.Y)
    ElseIf Label1.Location.X > Me.Width Then
        Label1.Location = New Point(0, Label1.Location.Y)
    End If
End Sub

Upvotes: 0

Views: 3031

Answers (1)

Richard
Richard

Reputation: 109005

The KeyDown event occurs each time a single key is pressed. Therefore you'll need to remember when a cursor key is pressed on once occurrence of KeyDown to check in another occurrence for another cursor key being pressed.

Remember to subscribe to KeyUp events to clear the state because the use could press one cursor key, release it and then press another.

Your code will never work:

ElseIf e.KeyCode = Keys.Up And e.KeyCode = Keys.Right Then

because this cannot be true. KeyCode is a single key code, it cannot be both one key and another.

Upvotes: 1

Related Questions