RexPRGMER
RexPRGMER

Reputation: 227

Horazontal scroll bar moving a picture box Microsoft VB

I have a little pong game im making and I want to make the "Paddle" which is just a picture box move up and down when I move a scroll bar left and right. My code for the Scroll Bar is here:

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

The paddle only seems to go up, but when I move the paddle to the left shouldn't it go down? Have the default value set for 50 and the maximum at 100

Upvotes: 1

Views: 1229

Answers (1)

Ccorock
Ccorock

Reputation: 892

Its because you need to account for which way the the scroll is happening. You'll always return a positive number with the code you have, instead you need to subtract from its current position.

 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

Another Solution I found to work better...

  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

Upvotes: 2

Related Questions