如何使对象仅在给定空间中移动?

时间:2014-10-08 05:02:12

标签: vb.net

我有关于VB.net编程的问题,特别是在keydown事件时移动对象。

所以情况就是这样。我在一个面板中放置了一个图片框,并使该图片框在keydown时移动了一定的距离。问题是图片框似乎与面板重叠(穿过墙)。 我认为面板的宽度与代码有关,以限制对象通过面板。不幸的是,我似乎无法找到应该采用什么方法来实现它。

到目前为止,这是我的代码:

Private Sub EClassic_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
        Case Keys.Left
            play_avatar.Left -= 100
            If play_avatar.Left = -200 Then
                Keys.Left. = Nothing
            End If
        Case Keys.Right
            play_avatar.Left += 100
            If play_avatar.Left = 200 Then
                Keys.Left. = Nothing
            End If
    End Select
End Sub

非常感谢您的回复!谢谢。

编辑:

我认为这很好,谢谢@Lolo。虽然我的编码看起来很便宜lol。

Dim c As Integer = Panel1.ClientSize.Width
    Dim res As Integer
    Dim res2 As Integer
    res2 = c - c + 100
    res = c / 2

    Select Case e.KeyCode
        Case Keys.Left
            If play_avatar.Left > res2 Then
                play_avatar.Left -= 100
            ElseIf play_avatar.Left < res2 Then
                play_avatar.Left -= 0
            End If

        Case Keys.Right
            If play_avatar.Left < res Then
                play_avatar.Left += 100
            ElseIf play_avatar.Left > res Then
                play_avatar.Left -= 0

            End If

    End Select

1 个答案:

答案 0 :(得分:0)

试试这个:

Private Sub EClassic_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
  Dim tmpLeft as integer

  Select Case e.KeyCode
    Case Keys.Left
      tmpLeft =play_avatar.Left - 100

      If tmpLeft < YourPanel.Left then
       e.cancel=true
      else
        play_avatar.Left = tmpLeft 
      End If

    Case Keys.Right
      tmpLeft =play_avatar.Left + 100

      If play_avatar.Right > YourPanel.Right then
        e.cancel=true
      else
         play_avatar.Left = tmpLeft 
      End If

    End Select
End Sub