I am working on collision for a pong clone i am working on. I set up a rectangle for the ball and the paddles and when those intersect, I want to invert the X or Y direction the ball is moving based on the area of the ball that collides with the paddle.
Examples. bottom of ball hits the top of the paddle invert the Y direction of motion, or right side of ball hits the left side of paddle invert X direction of motion.
So after the collision call happens I created 4 rectangles representing the ball 1 for each 4th of the ball: top left, top right, bottom left, and bottom right. and set up if statements to check for intersection between those and the paddle rectangle.
here is the collision code i have
private void checkPaddleCollision(List<Paddle> paddles)
{
CollisionType type = CollisionType.Left;
bool collide = false;
Paddle paddle = new Paddle();
foreach (Paddle p in paddles)
{
if(rect.Intersects(p.Bounds))
{
paddle = p;
collide = true;
Rectangle topLeft, topRight, bottomLeft, bottomRight;
int height = rect.Height / 2;
int width = rect.Width / 2;
topLeft = new Rectangle(rect.X, rect.Y, width, height);
topRight = new Rectangle(rect.X + width, rect.Y, width, height);
bottomLeft = new Rectangle(rect.X, rect.Y + height, width, height);
bottomRight = new Rectangle(rect.X + width, rect.Y + height, width, height);
if((p.Bounds.Intersects(topLeft) || p.Bounds.Intersects(topRight)) &&(!p.Bounds.Intersects(bottomLeft) || !p.Bounds.Intersects(bottomRight)))
{
type = CollisionType.Top;
}
else if ((p.Bounds.Intersects(bottomLeft) || p.Bounds.Intersects(bottomRight)) && (!p.Bounds.Intersects(topLeft) || !p.Bounds.Intersects(topRight)))
{
type = CollisionType.Bottom;
}
else if ((p.Bounds.Intersects(bottomLeft) || p.Bounds.Intersects(topLeft)) && (!p.Bounds.Intersects(topRight) || !p.Bounds.Intersects(bottomRight)))
{
type = CollisionType.Left;
}
else if ((p.Bounds.Intersects(bottomRight) || p.Bounds.Intersects(topRight)) && (!p.Bounds.Intersects(topLeft) || !p.Bounds.Intersects(bottomLeft)))
{
type = CollisionType.Right;
}
}
}
if (collide)
{
switch (type)
{
case CollisionType.Left:
position.X = paddle.Position.X + paddle.Bounds.Width;
break;
case CollisionType.Right:
position.X = paddle.Position.X - texture.Width;
break;
case CollisionType.Bottom:
position.Y = paddle.Position.Y + texture.Height;
break;
case CollisionType.Top:
position.Y = paddle.Position.Y + paddle.Bounds.Height;
break;
}
if (type == CollisionType.Left || type == CollisionType.Right)
{
direction.X *= -1;
direction.Normalize();
}
else
{
direction.Y *= -1;
direction.Normalize();
}
}
}
The collision works fine when the ball hits the top or bottom of a paddle but it is not regestering correctly when it hits the left or right of a paddle. It sees it as either top or bottom until the ball is halfway through the paddle then it regesters. can anyone point me in the right direction. Thanks.