I am trying to create a simply bouncy ball application in VB net;
I am using a timer and the FillEllipse() method to try ad create a new circle at every tick of the timer.
Code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim Gr As Graphics = Me.CreateGraphics
Gr.FillEllipse(Brushes.Teal, X, Y, W, H)
CollisionDetect()
X = X + X_Dir
Y = Y + Y_Dir
Gr.Dispose()
End Sub
The result? The form continously draws onto itself, without clearing the last circle. This means that you end up with a ‘line’ of spheres together.
To clarify:
X is well, the X-Coords
Y is Y- Y-Coords
X_Dir is an integer, it is added to every iteration of the loop so the next time the loop iterates, it’ll be at a different location;
Y_Dir is the same but for the Y Coords;
CollisionDetect() Is empty. It is yet to be filled, it will handle the collision with the sides of the forms.
W, H are width and height, respectively.
Ideas?
Usually painting is done when the Paint event is fired. Add a
Panelcontrol with the desired background color to your form. Handle thePaintevent of your panelThe panel will always automatically be cleared before you draw.
Change the timer tick event handler to
Note that the Paint event is fired automatically, if the panel was hidden by another form, for instance, and has to be redrawn. If the computer is busy and cannot paint, some paint events may be skipped. Therefore keep your game logic (calculation) in
Timer1_Tick.If you prefer to draw directly on the form, you can do that by using the form’s paint event instead of the panel’s paint event and by calling
Me.Invalidate()instead ofPanel1.Invalidate().