Bouncing Ball Tutorial - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This is a tutorial on how to make a bouncing ball in Visual Basic .NET

Add a picture box to the form:

use a transparent picture for this tutorial, Click Here to download this transparent earth pic

Add the picture to your picture box:

Change also Size Mode to Zoom

Add 4 timers to the form. Change their interval property to 1

Change also the first timer Enabled property to True

Let's add the code to each timer tick event:

Timer1 Tick Event

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        PictureBox1.Location = New Point(PictureBox1.Location.X + 5, PictureBox1.Location.Y + 5)
        If PictureBox1.Location.X + PictureBox1.Width > Me.Width Then
            Timer1.Stop()
            Timer2.Start()
        End If

        If PictureBox1.Location.Y + PictureBox1.Height > Me.Height Then
            Timer1.Stop()
            Timer3.Start()
  End If
    End Sub

Timer2 Tick Event

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        PictureBox1.Location = New Point(PictureBox1.Location.X - 5, PictureBox1.Location.Y + 5)
        If PictureBox1.Location.Y + PictureBox1.Height > Me.Height Then
            Timer2.Stop()
            Timer4.Start()
        End If
        If PictureBox1.Location.X < 0 Then
            Timer2.Stop()
            Timer1.Start()
        End If
    End Sub

Timer3 Tick Event

Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick
        PictureBox1.Location = New Point(PictureBox1.Location.X + 5, PictureBox1.Location.Y - 5)
        If PictureBox1.Location.X + PictureBox1.Width > Me.Width Then
            Timer3.Stop()
            Timer4.Start()
        End If
        If (PictureBox1.Location.Y < 0) Then
            Timer3.Stop()
            Timer1.Start()
        End If
    End Sub

Timer4 Tick Event

Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer4.Tick
        PictureBox1.Location = New Point(PictureBox1.Location.X - 5, PictureBox1.Location.Y - 5)
        If PictureBox1.Location.X < 0 Then
            Timer4.Stop()
            Timer3.Start()
        End If
        If (PictureBox1.Location.Y < 0) Then
            Timer4.Stop()
            Timer2.Start()
        End If
    End Sub


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.