diff --git a/include/misc/Shapes.h b/include/misc/Shapes.h index 92aeee3..1483b46 100644 --- a/include/misc/Shapes.h +++ b/include/misc/Shapes.h @@ -53,6 +53,10 @@ public: bool collidesWith(const Point& point) const; bool collidesWith(const Rectangle& rect) const; bool collidesWith(const Circle& circle) const; + + // distance from the closest side of the rectangle + float distance(const Circle& circle) const; + float distanceSquared(const Circle& circle) const; }; class Circle { @@ -78,6 +82,10 @@ public: bool collidesWith(const Point& point) const; bool collidesWith(const Rectangle& rect) const; bool collidesWith(const Circle& circle) const; + + // distance from the closest side of the rectangle + float distance(const Rectangle& rect) const; + float distanceSquared(const Rectangle& rect) const; }; } // namespace shape diff --git a/src/misc/Shapes.cpp b/src/misc/Shapes.cpp index b1801ae..505cca7 100644 --- a/src/misc/Shapes.cpp +++ b/src/misc/Shapes.cpp @@ -39,6 +39,14 @@ bool Rectangle::collidesWith(const Circle& circle) const { return circle.collidesWith(*this); } +float Rectangle::distance(const Circle& circle) const { + return circle.distance(*this); +} + +float Rectangle::distanceSquared(const Circle& circle) const { + return circle.distanceSquared(*this); +} + @@ -48,21 +56,29 @@ bool Circle::collidesWith(const Point& point) const { } bool Circle::collidesWith(const Rectangle& rect) const { - float closestX = std::clamp(m_Center.getX(), rect.getTopLeft().getX(), rect.getBottomRight().getX()); - float closestY = std::clamp(m_Center.getY(), rect.getTopLeft().getY(), rect.getBottomRight().getY()); + float distanceSquared_ = distanceSquared(rect); - float distanceX = m_Center.getX() - closestX; - float distanceY = m_Center.getY() - closestY; - - float distanceSquared = (distanceX * distanceX) + (distanceY * distanceY); - - return distanceSquared < m_Radius * m_Radius; + return distanceSquared_ < m_Radius* m_Radius; } bool Circle::collidesWith(const Circle& circle) const { return m_Radius + circle.getRadius() > m_Center.distanceSquared(circle.getCenter()); } +float Circle::distance(const Rectangle& rect) const { + return std::sqrt(distanceSquared(rect)); +} + +float Circle::distanceSquared(const Rectangle& rect) const { + float closestX = std::clamp(m_Center.getX(), rect.getTopLeft().getX(), rect.getBottomRight().getX()); + float closestY = std::clamp(m_Center.getY(), rect.getTopLeft().getY(), rect.getBottomRight().getY()); + + float distanceX = m_Center.getX() - closestX; + float distanceY = m_Center.getY() - closestY; + + return (distanceX * distanceX) + (distanceY * distanceY); +} + } // namespace shape } // namespace utils } // namespace td