+8

Circle-rectangle collisions

I've been looking for a whole day looking at how to detect the collisions between a circle and a rectangle, please if you have any solution apply it to the following code https://code.sololearn.com/WffWtTr5sPJb/?ref=app

6/24/2019 4:18:29 AM

InvBoy [ :: FEDE :: ]

3 Answers

New Answer

+6

Whether the distance between two center points is shorter than sum of each center-edge length at that direction. https://code.sololearn.com/Wox0V9foOMk4/?ref=app Edge Tracking, by Morpheus https://code.sololearn.com/WCwKdRy210Ga/?ref=app

+6

I think your circle and rectangle are designed in this way: Circle: center x center y radius Rectangle: left x top y height width If this is correct then here is a thought. The equation of a circle is: (x-x0)^2+(y-y0)^2=r^2 Now try to find any point in the rectangle that will satisfy the equation. If your circle and rectangle behave in a fixed way I could simplify this.

+4

function collisionRectangleCircle(rectangle, circle){ return ( collisionRectanglePoint(rectangle, circle.getMiddleX(), circle.getMiddleY() - circle.getRadius()) || collisionRectanglePoint(rectangle, circle.getMiddleX(), circle.getMiddleY() + circle.getRadius()) || collisionRectanglePoint(rectangle, circle.getMiddleX() - circle.getRadius(), circle.getMiddleY()) || collisionRectanglePoint(rectangle, circle.getMiddleX() + circle.getRadius(), circle.getMiddleY()) || collisionRectanglePoint(rectangle, circle.getMiddleX(), circle.getMiddleY()) || collisionCirclePoint(circle, rect.getMiddleX() - rect.getWidth()/2, rect.getMiddleY() - rect.getHeight()/2) || collisionCirclePoint(circle, rect.getMiddleX() - rect.getWidth()/2, rect.getMiddleY() + rect.getHeight()/2) || collisionCirclePoint(circle, rect.getMiddleX() + rect.getWidth()/2, rect.getMiddleY() - rect.getHeight()/2) || collisionCirclePoint(circle, rect.getMiddleX() + rect.getWidth()/2, rect.getMiddleY() + rect.getHeight()/2) ); } function collisionRectanglePoint(rectangle, x, y){ return (x > rectangle.getMiddleX() - rectangle.getWidth()/2 && x < rectangle.getMiddleX() + rectangle.getWidth()/2 && y > rectangle.getMiddleY() - rectangle.getHeight()/2 && y < rectangle.getMiddleY() + rectangle.getHeight()/2); } function collisionCirclePoint(cirlce, x, y){ return (Math.sqrt(Math.pow(circle.getMiddleX() - x, 2) + Math.pow(circle.getMiddleY() - y, 2)) < cirlce.getRadius()); }