0

I have been creating a game using C++ and the graphics library SFML. I want a boolean method to check if there is a collision between a sf::CircleShape and a sf::RectangleShape given those two objects as parameters. The problem is that the objects are not axis aligned. How would I create the method?

My attempt at the method (but it only works for axis aligned shapes):

bool checkCollision(CircleShape circle, RectangleShape rectangle)
{
        double circleDistanceX = abs(circle.getPosition().x - rectangle.getPosition().x);
        double circleDistanceY = abs(circle.getPosition().y - rectangle.getPosition().y);

        if (circleDistanceX > (rectangle.getSize().x/2 + circle.getRadius()))
        {
                return false;
        }
        if (circleDistanceY > (rectangle.getSize().y/2 + circle.getRadius()))
        {
                return false;
        }

        if (circleDistanceX <= (rectangle.getSize().x/2))
        {
                return true;
        }
        if (circleDistanceY <= (rectangle.getSize().y/2))
        {
                return true;
        }

        double cornerDistance_sq = pow((circleDistanceX - rectangle.getSize().x/2), 2) + pow((circleDistanceY - rectangle.getSize().y/2),2);

        return (cornerDistance_sq <= pow((circle.getRadius()),2));

}
user3236245
  • 75
  • 1
  • 1
  • 5
  • How can a circle not be axis aligned? Surely you just need to check each point of the rect to know if its within the circle? Or line segment to circle collision test/ – paulm Feb 02 '14 at 22:05
  • Here is an old post that might help you. https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection – Rodolphe Chartier May 27 '17 at 14:56

1 Answers1

0

This is supposed to be a comment, but it seems that my reputation is too low. If I were you I would check out the SAT method as it is really cool and can be used to check for separation between any shape including a rectangle and a circle. Here is a tutorial with a working source code example: http://content.gpwiki.org/VB:Tutorials:Building_A_Physics_Engine:Basic_Intersection_Detection

Also this site has some really cool examples on how it works:

http://www.metanetsoftware.com/technique/tutorialA.html