Collision detection in C#.Net & Java example

Suppose we are making a game that deals with collision of objects moving around the screen, like a simple pong game or maybe a physics simulation. Implementing collision detection in C# is very simple to do. In this example we have a ball and a racket sprites that are moving on the screen. If the ball is to collide with the racket, then it bounces off, if it goes past the racket the game ends. The function that is the center of this concept is .Intersect() or .IntersectsWith(). In Java, its also the same name as well.

With C# we will be making a Windows Form app with a picturebox control to display the game. In Java the code for this demo is somewhat similar but a different approach.

Java version here

The C# approach uses Windows Forms (a picturebox control to display the simulation, a timer control used for ball animation). With this approach its very easy to understand code as we have a MoveBall() method that will act as the main function to move the ball using velocites of the ball (int dy,dx fields), DrawBall() draws the ball sprite in the picturebox, finally the timer tick event handler will call MoveBall() for every 1 ms of elapsed event. For our collision detection, we will use .IntersectsWith() to detect a collision and have some code that reacts to the collision. Finally we will use Rectangles for our racket and ball sprites.


public partial class Form1 : Form
        Rectangle racket;//our racket sprite
        Rectangle ball;//our ball sprite
        int dx, dy;
        int hitCount;
        public Form1()
            racket = new Rectangle(120, 270, 60, 10);//sprite initialization
            ball = new Rectangle(140, 10, 20, 20);
            dx = 5;//initial speeds
            dy = 5;
            hitCount = 0;

        private void pictureBox1_Paint(object sender, PaintEventArgs e)//paint event handler to display the graphics using the picturebox
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//for smoother graphics/shapes
            e.Graphics.FillRectangle(new SolidBrush(Color.RoyalBlue), racket);
            e.Graphics.DrawString("score: " + hitCount, DefaultFont, new SolidBrush(Color.Black), new Point(1, 1));

            DrawBall(e);//draws the ball

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)//mouse event handler to move the racket
            racket.X = e.X;
            if (racket.Right > pictureBox1.Right) { racket.X = pictureBox1.Right - racket.Width; }
            Refresh();//refresh the control to display the new position of the racket
        private void DrawBall(PaintEventArgs e)
            e.Graphics.FillEllipse(new SolidBrush(Color.Red), ball);
        private void MoveBall()//this method handles ball movement within the screen
            if (ball.X + dx < 0)
                dx += 10;
            if (ball.X + dx >= pictureBox1.Width)
                dx -= 10;
            if (ball.Y + dy < 0)
                dy += 5;
                if (dy == 0) { dy += 5; }
            if (ball.Y + dy >= pictureBox1.Height)//game over handling if the ball goes past the racket & collides with the bottom of the screen
                dx = 0;//set the speeds to zero
                dy = 0;

                var gameOver = MessageBox.Show("GAME OVER", "Message",MessageBoxButtons.OK);//show a message displaying game over
                if (gameOver == System.Windows.Forms.DialogResult.OK)
                    Close();//close the program
            if (ball.IntersectsWith(racket))//COLLISION DETECTED!
                dy -= 10;
                hitCount+=1;//increment after every hit
            ball.X = ball.X + dx;//update the ball x position
            ball.Y = ball.Y + dy;//update the ball y position

        private void timer1_Tick(object sender, EventArgs e)//the timer is very important, it acts as the main tool for animation
            timer1.Interval = 1; //sets the frequency of elapsed events in milliseconds, important to set it 1 ms for smooth animation
            timer1.Enabled = true; //enable the timer
            MoveBall();//call move ball to update location
            Refresh();//refresh the environment


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