Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Ball Animation with Border Collision using VS 2005 and .NET 2.0

0.00/5 (No votes)
12 May 2006 1  
A very primitive article on simple animation of balls using double buffering technique
Sample Image - BallAnimation.jpg

Introduction

In this project, I have demonstrated a simple technique on how we can animate some balls in a Picture Box. The balls collides with the walls and change directions. Using the double buffering of .NET 2.0, it is very easy to handle large processing of graphical animation.

I have created a Ball class which can be reused and extended for other projects as well. The Ball class has the following methods:

DrawBall(Graphics g) 
DrawBall(Graphics g, int move_x, int move_y) 
MoveBall(Ball ball, int screenHeight, int screenWidth)

The DrawBall with the single parameter draws an ellipse on the Graphics object. On the other hand, the Drawball with three parameters draws the updated ball on the screen.

The ball is created using the following code:

g.DrawEllipse(new Pen(_ballColor), _x, _y, _width, _height);
// Create solid brush. 
SolidBrush redBrush = new SolidBrush(_ballColor); 
// Fill ellipse on screen
g.FillEllipse(redBrush, _x, _y, _width, _height);

The double buffering is achieved by the following code:

this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
this.SetStyle(ControlStyles.UserPaint, true); 

We have used a timer with interval 1 millisecond to animate the balls. In the Timer Tick method I used:

for (int i = 0; i < TOTAL_BALLS; i++) 
{
    manyBall[i].MoveBall(
       manyBall[i],
       pictureBox1.Height, 
       pictureBox1.Width
    ); 
} 
this.Refresh();

To Refresh the picture box on where we are painting the balls, I wrote:

private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) 
{
    for(int i = 0; i < TOTAL_BALLS; i++) 
    { 
        manyBall[i].DrawBall(e.Graphics); 
    } 
}

Conclusion

We have seen how we can animate balls using simple animation techniques. Hope you like the code. Till then, Eat Bytes Regularly for good health.

History

  • 13th May, 2006: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here