BLOG.CSHARPHELPER.COM: Make a bouncing ball animation in C#
Make a bouncing ball animation in C#
When the form loads, the following code initializes the ball's position and velocity to random values. It also turns on the form's DoubleBuffer style to reduce flicker.
// Some drawing parameters. private const int BALL_WID = 50; private const int BALL_HGT = 50; private int BallX, BallY; // Position. private int BallVx, BallVy; // Velocity.
// Initialize some random stuff. private void Form1_Load(object sender, EventArgs e) { // Pick a random start position and velocity. Random rnd = new Random(); BallVx = rnd.Next(1, 4); BallVy = rnd.Next(1, 4); BallX = rnd.Next(0, this.ClientSize.Width - BALL_WID); BallY = rnd.Next(0, this.ClientSize.Height - BALL_HGT);
// Use double buffering to reduce flicker. this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); this.UpdateStyles(); }
When the form's Timer fires its Tick event, the following code moves the ball.
This code adds the ball's velocity (in pixels per timer interval) to the ball's position. If the ball crosses a form edge, the code switches the velocity's component in the corresponding direction (depending on which edge it hit). After moving the ball, the code invalidates the form to make the following Paint event handler redraw the ball at its new position.
// Draw the ball at its current location. private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.Clear(this.BackColor); e.Graphics.FillEllipse(Brushes.Blue, BallX, BallY, BALL_WID, BALL_HGT); e.Graphics.DrawEllipse(Pens.Black, BallX, BallY, BALL_WID, BALL_HGT); }
When the ball hits a form edge, the code also calls the following Boing method, which plays an audio resource.
// Play the boing sound file resource. private void Boing() { using (SoundPlayer player = new SoundPlayer( Properties.Resources.boing)) { player.Play(); } }
Comments