0
votes

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

1
Hi, welcome on StackOverflow! I think you should show how your implementation of this triangle and collision exactly looks like, because it's too more to guess for now.Karol Selak

1 Answers

0
votes

Two of possible ways:

1) Get circle center coordinates in rotated coordinate system defined by rectangle and use known approach. To transform coordinates, calculate (Fi is rotation angle)

tx = circle.x - rectanglecenter.x
ty = circle.y - rectanglecenter.y
cx = rectanglecenter.x + tx * Cos(Fi) + ty * Sin(Fi)
cy = rectanglecenter.y - tx * Sin(Fi) + ty * Cos(Fi)

Arbitrary found JS example

2) Calculate length of projections of vector CR=circle-rectanglecenter onto direction vectors which components are (Cos(Fi), Sin(Fi)) and (-Sin(Fi), Cos(Fi)) using scalar product

distX' = Abs(Cos(Fi)*CR.x + Sin(Fi)*CR.y)
distY' = Abs(-Sin(Fi)*CR.x + Cos(Fi)*CR.y)

and then use these distances