Hello GameDev stack exchange!
I'm adapting a rectangle to circle collision detection algorithm from the second (not the accepted) answer from here: https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection. This is C++ code. Here is my adaptation:
bool Collision::checkCircleToRectCollision(sf::CircleShape circle, float rectX, float rectY, float width, float height)
{
sf::Vector2f circleDistance;
circleDistance.x = std::abs((circle.getPosition().x - rectX) + circle.getRadius());
circleDistance.y = std::abs((circle.getPosition().y - rectY) + circle.getRadius());
if (circleDistance.x > (width / 2 + circle.getRadius())) {
return false;
}
if (circleDistance.y > (height / 2 + circle.getRadius())) {
return false;
}
if (circleDistance.x <= (width / 2)) {
return true;
}
if (circleDistance.y <= (height / 2)) {
return true;
}
float cornerDistance = ((circleDistance.x - width / 2) * (circleDistance.x - width / 2)) +
((circleDistance.y - height / 2) * (circleDistance.y - height / 2));
return cornerDistance <= (circle.getRadius() * circle.getRadius());
}
The problem is the collision detects only the lower right section of the circle. Without the + circle.getRadius()
inside of circleDistance.x = std::abs((circle.getPosition().x - rectX)
the algorithm detects even less area. Here is a a picture to visualize. I want the algorithm to detect the entire blue area. It currently only detects the red area. This is a an approximate, but very accurate from what I can tell. The white box is my players hitbox.
I've spent a few days googling and this is the closest I've gotten, but now I'm stuck. How can I make the algorithm detect the entire blue circle? Thanks in advance! :)
sqrt((x2-x1)^2 + (y2-y1)^2)
) \$\endgroup\$ – clabe45 Aug 22 '17 at 18:56cornerDistance_sq = (circleDistance.x - rect.width/2)^2 + (circleDistance.y - rect.height/2)^2; return (cornerDistance_sq <= (circle.r^2));
\$\endgroup\$ – clabe45 Aug 22 '17 at 19:01