|
|
Title | Make a bouncing ball animation in VB .NET |
Description | This example shows how to make a bouncing ball animation in VB .NET. |
Keywords | bouncing ball, animation, animate, VB.NET |
Categories | Algorithms, Graphics, Controls |
|
|
When the form loads, initialize the ball's position and direction vector . Turn on the form's DoubleBuffer style to reduce flicker.
|
|
Private Const BALL_WID As Integer = 50
Private Const BALL_HGT As Integer = 50
Private m_Dx As Integer
Private m_Dy As Integer
Private m_X As Integer
Private m_Y As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
Dim rnd As New Random
m_Dx = rnd.Next(1, 4)
m_Dy = rnd.Next(1, 4)
m_X = rnd.Next(0, Me.ClientSize.Width - BALL_WID)
m_Y = rnd.Next(0, Me.ClientSize.Height - BALL_HGT)
Me.SetStyle( _
ControlStyles.AllPaintingInWmPaint Or _
ControlStyles.UserPaint Or _
ControlStyles.DoubleBuffer, _
True)
Me.UpdateStyles()
End Sub
|
|
When the form's Timer fires its Tick event, add m_Dx and m_Dy to the ball's position. If the ball crosses form edge, switch the direction of m_Dx or m_Dy. After moving the ball, invalidate the form to force a Paint event.
In the Paint event, clear the form and redraw the ball.
|
|
Private Sub tmrMoveBall_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles tmrMoveBall.Tick
m_X += m_Dx
If m_X < 0 Then
m_Dx = -m_Dx
Beep()
ElseIf m_X + BALL_WID > Me.ClientSize.Width Then
m_Dx = -m_Dx
Beep()
End If
m_Y += m_Dy
If m_Y < 0 Then
m_Dy = -m_Dy
Beep()
ElseIf m_Y + BALL_HGT > Me.ClientSize.Height Then
m_Dy = -m_Dy
Beep()
End If
Me.Invalidate()
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles _
MyBase.Paint
e.Graphics.Clear(Me.BackColor)
e.Graphics.FillEllipse(Brushes.Blue, m_X, m_Y, _
BALL_WID, BALL_HGT)
e.Graphics.DrawEllipse(Pens.Black, m_X, m_Y, BALL_WID, _
BALL_HGT)
End Sub
|
|
|
|
|
|