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.

// Update the ball's position, bouncing if necessary.
private void tmrMoveBall_Tick(object sender, EventArgs e)
{
BallX += BallVx;
if (BallX < 0)
{
BallVx = -BallVx;
Boing();
} else if (BallX + BALL_WID > this.ClientSize.Width)
{
BallVx = -BallVx;
Boing();
}

BallY += BallVy;
if (BallY < 0)
{
BallVy = -BallVy;
Boing();
} else if (BallY + BALL_HGT > this.ClientSize.Height)
{
BallVy = -BallVy;
Boing();
}

this.Invalidate();
}

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();
}
}

For more information on creating and playing audio resources, see Play an audio resource in C#.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.