Spin
Spin

Reputation: 13

Picture box gets stuck when moving up and down

I'm currently creating a side shooter game and I'm trying to get the enemy to go up and down. It kind of works but when it reaches the bottom of the form instead of going up it just bounces in place at the bottom. I have no clue how to fix this.

Private Sub tmrEnemy_Tick(sender As Object, e As EventArgs) Handles tmrEnemy.Tick
    If enemy.Top >= 445 Then
        enemy.Top -= 5
    Else
        enemy.Top += 5
    End If
End Sub

Upvotes: 1

Views: 35

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

The problem is that you're basing your decision whether to go up or down on the fact that the picture has reached the bottom. So when that happens, you move the picture up and next time it's no longer at the bottom so it will move down again.

A simple solution can be by using a variable to track the direction in which the picture is moving. It can be 1 when the picture is moving down, and -1 when moving up. Something like this:

Dim Direction As Integer = 1;

Private Sub tmrEnemy_Tick(sender As Object, e As EventArgs) Handles tmrEnemy.Tick
    If enemy.Top >= 445 Then 'Reached the bottom, go up.
        direction = -1
    Else If enemy.Top <= 0 Then 'Reached the top, go down.
        direction = 1
    End If

    enemy.Top += direction * 5
End Sub

Upvotes: 1

Related Questions