水平滚动条移动图片框Microsoft VB

时间:2014-02-26 23:48:45

标签: vb.net picturebox

我正在制作一个小乒乓球游戏,我想制作“Paddle”,当我向左和向右移动滚动条时,它只是一个图片框上下移动。我的Scroll Bar代码在这里:

Private Sub HScrollBar1_Scroll(sender As Object, e As ScrollEventArgs) Handle HScrollBar1.Scroll Me.picPlayer1.Location = New Point(Me.picPlayer2.Location.X, Me.picPlayer2.Location.Y - HscrollBar1.Value * 1) End Sub

桨只似乎上升,但当我向左移动桨不应该下降?将默认值设置为50,将最大值设置为100

1 个答案:

答案 0 :(得分:2)

这是因为您需要考虑滚动发生的方式。您将始终使用您拥有的代码返回正数,而是需要从当前位置中减去。

 Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll

    Dim NewPos As Integer = e.NewValue
    Dim OldPos As Integer = e.OldValue

    Debug.WriteLine(NewPos, "My Current Value")
    Debug.WriteLine(OldPos, "My Previous Value")

    If NewPos > OldPos Then
        'Moving Up
        Me.PicPlayer1.Location = New Point(Me.PicPlayer1.Location.X, Me.PicPlayer1.Location.Y - HScrollBar1.Value * 1)
    Else
        'Moving Down
        Me.PicPlayer1.Location = New Point(Me.PicPlayer1.Location.X, Me.PicPlayer1.Location.Y - HScrollBar1.Value * -1)
    End If

End Sub

我发现另一种解决方案可以更好地工作......

  Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll

        Dim NewPos As Integer = e.NewValue
        Dim OldPos As Integer = e.OldValue

        Debug.WriteLine(NewPos, "My Current Value")
        Debug.WriteLine(OldPos, "My Previous Value")

        Dim delta As Integer = Math.Abs(NewPos - OldPos)

        If NewPos > OldPos Then
            'Moving up
            Me.PicPlayer1.Location = New Point(Me.PicPlayer1.Location.X, Me.PicPlayer1.Location.Y - delta)
        Else

            'Moving down
            Me.PicPlayer1.Location = New Point(Me.PicPlayer1.Location.X, Me.PicPlayer1.Location.Y + delta)
        End If

    End Sub