I am trying to detect collision between a circle and a rectangle using the distance between their centers. The collision detection works fine all the time except when I detect the collision of the circle with a rotated rectangle. The circle collides with the precious positions of the rectangle. I want it to collide with the newly rotated rectangle.
I am using rotate() function along with Math.PI(angle * Math.PI/180)
This is the code that i use for detection of collision:
function paddleCircleColliding(circle, paddle) {
// this is the distance btw the center of the ball and the center of the any rectangle
let distX = Math.abs(circle.x - paddle.x - paddle.w / 2);
let distY = Math.abs(circle.y - paddle.y - paddle.h / 2);
// this compares the distance with the sum of half the width of the rectangle and the radius of the circle
if (distX > (paddle.w / 2 + circle.r)) {
return false;
}
if (distY > (paddle.h / 2 + circle.r)) {
return false;
}
// this compares the distance with half the width of the rectangle
if (distX <= (paddle.w / 2)) {
return true;
}
// this compares the distance with half the height of the rectangle
if (distY <= (paddle.h / 2)) {
return true;
}
// this is to check if the ball hits the corner of the rectangle
let dx = distX - paddle.w / 2;
let dy = distY - paddle.h / 2;
return (dx * dx + dy * dy <= (circle.r * circle.r));
}
it works like a charm when i test it without rotating the rectangle using the rotate function given above but when I rotate the surface and test the collision detection, the ball seems to collide with an invisible surface where the rectangle used to be.
Thanks