RDR RDR - 7 months ago 52
Vb.net Question

PictureBox moving left to right to left repeatedly

Trying to use this code so that the picturebox will move from left to right by itself automatically. The code doesn't give any errors but when I run the app, the picturebox1 just stays still and does nothing.

I'm thinking: Timer1 properties maybe, didn't mess with anything in the timer1 properties, not sure if I'm supposed to, or maybe I have to add more code or fix it; not sure.

(If you are curious what I'm doing in case that helps, I'm having an 'enemy' move back and forth from left to right to left to right and so on, and the 'player' has to get past it without hitting it.)

Private Sub Timer1_Timer()
Do
PictureBox1.Left = PictureBox1.Left - 5
If PictureBox1.Left <= 5 Then
Do
PictureBox1.Left = PictureBox1.Right + 5
Loop Until PictureBox1.Left >= 1000
End If
Loop
End Sub

Answer

As @user3697824 mentioned, the Sub you posted is not connected to the Timer on your form. Generally when using timers, you put the code you want to run in the Timer's Tick method.

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    'Your code goes here.
End Sub

You could potentially fix your code above by adding a Handles Timer1.Tick statement to the end of the Sub's signature like this:

Private Sub Timer1_Timer() Handles Timer1.Tick
    Do
        PictureBox1.Left = PictureBox1.Left - 5
        If PictureBox1.Left <= 5 Then
            Do
                PictureBox1.Left = PictureBox1.Right + 5
            Loop Until PictureBox1.Left >= 1000
        End If
    Loop
End Sub