# 2D circle / rectangle collision detection issue - brief overlap

I'm currently trying to build a Breakout clone as a first step into game development. I'm using the following collision detection code (adapted from https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection). I have a rectangle and a circle, and the following C# code:

       Point circleDistance = new Point(Math.Abs(ball.collisionRect.Center.X - block.collisionRect.Center.X), Math.Abs(ball.collisionRect.Center.Y - block.collisionRect.Center.Y));

if (circleDistance.X > (block.collisionRect.Width / 2 + ball.collisionRect.Width / 2)) { return false; }
if (circleDistance.Y > (block.collisionRect.Height / 2 + ball.collisionRect.Height / 2)) { return false; }

if (circleDistance.X <= (block.collisionRect.Width / 2)) { return true; }
if (circleDistance.Y <= (block.collisionRect.Height / 2)) { return true; }

float cornerDistance_sq = (circleDistance.X - block.collisionRect.Width / 2) ^ 2 + (circleDistance.Y - block.collisionRect.Height / 2) ^ 2;
Console.WriteLine("Corner dist = " + cornerDistance_sq);
return (cornerDistance_sq <= ((ball.collisionRect.Height / 2) ^ 2));


The ball moves automatically, and the rectangle is controlled using the keyboard.

When a collision occurs, I'm simply inverting the X and Y components of the ball's speed vector.

Occasionally, however, when the rectangle is moving and collides with the ball on its left or right edge, it gets 'caught', and overlaps by more than a few pixels. This results in several collisions in quick succession, and the ball 'jitters' until the rectangle is moved out of the way.

You can see the overlap at http://imgur.com/m8g5W

I'm not sure why this occurs - if I add a boolean variable 'previousCollide' that is set on collide, then stop inverting the vector if this is set, then unset it once collisions have stopped occurring, then whilst there is still visible overlap the 'jitters' go away.

How can I prevent this?