Balls bouncing and colliding on the screen

Just a small graphical application i made in my free time.
The program has a ball form which is called in a loop from the void main method.

We catch the paint event which is where the ball is drawn:

private void BallForm_Paint(object sender, PaintEventArgs e)
    Width = Convert.ToInt32(radios * 2); //24;
    Height = Convert.ToInt32(radios * 2); //24;

    Graphics g = e.Graphics;
    g.FillPie(new SolidBrush(col), 0, 0, Width - 1, Height - 1, 0, 360);
    g.DrawArc(new Pen(Color.Black,2), 0, 0, Width - 1, Height - 1, 0, 360);

the balls are under the force of gravity there for always pulled down, to get this effect every tick  the Y vector decreased in just a bit which simulated gravity and can be modified to have a stronger gravitational pull if increased

double gravity = 0.1;
moveY += gravity;

also the X vector is changed to simulate fraction
moveX *= 0.75;

balls that collide with one each other are calculated to bounce away in the opposite direction of the impact, in this case some physics is needed to calculate the direction of 2 collisions using the radios of the circles equation to find if one ball entered another balls radios space

double distIn = Math.Sqrt(Math.Pow((int)x1 - (int)x2, 2) + Math.Pow((int)y1 - (int)y2, 2));
m = (y2 - y1) / (x2 - x1);
double b = y1 - (m * x1);

and the velocity of the ball which absorbs the velocity from the ball it collided with
double difX = Math.Abs(oBall.moveX – moveX);
double difY = Math.Abs(oBall.moveY – moveY);

if right clicking on a ball a small menu will open and allow some functionality like make it bounce again(which will any way happen when the ball stops movement) the tricky part is to catch the right click event exactly when the pointer is over the ball good luck 🙂

here is the source code:

Visual studio 2005:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: