From 4afb92ceab6e26f484ce47db7b20a776bb900667 Mon Sep 17 00:00:00 2001 From: Alfred Burgess <aburgess@ucc.gu.uwa.edu.au> Date: Tue, 5 Dec 2023 13:18:44 +0800 Subject: [PATCH] Added Rectangle class to maths --- include/maths/maths.h | 1 + include/maths/rect.h | 26 ++++++++++++++++++++++++++ src/maths/rect.cpp | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 include/maths/rect.h create mode 100644 src/maths/rect.cpp diff --git a/include/maths/maths.h b/include/maths/maths.h index fea450c..0480836 100644 --- a/include/maths/maths.h +++ b/include/maths/maths.h @@ -2,5 +2,6 @@ #define __MATHEMATICS_INCLUDE_H__ #include "maths/vec2.h" +#include "maths/rect.h" #endif // __MATHEMATICS_INCLUDE_H__ diff --git a/include/maths/rect.h b/include/maths/rect.h new file mode 100644 index 0000000..fc836ea --- /dev/null +++ b/include/maths/rect.h @@ -0,0 +1,26 @@ +#ifndef __MATHS_RECT_H__ +#define __MATHS_RECT_H__ + +#include "maths/vec2.h" + +class Rect +{ + public: + Rect( float x, float y, float w, float h ); + Rect( Vec2 pt, float w, float h ); + ~Rect(){} + + bool isOverlap( Vec2 pt ); + bool isOverlap( Rect rect ); + + bool overlap_horizontal( Rect rect ); + bool overlap_vertical( Rect rect ); + + private: + Vec2 _pt; + float _halfWidth; + float _halfHeight; +}; + + +#endif // __MATHS_RECT_H__ diff --git a/src/maths/rect.cpp b/src/maths/rect.cpp new file mode 100644 index 0000000..855294e --- /dev/null +++ b/src/maths/rect.cpp @@ -0,0 +1,33 @@ +#include "maths/rect.h" + +Rect::Rect( float x, float y, float w, float h ) + : Rect( Vec2(x, y), w, h ) +{} +Rect::Rect( Vec2 pt, float w, float h ) + : _pt( pt ), + _halfWidth( w / 2 ), + _halfHeight( h / 2 ) +{} + +bool Rect::isOverlap( Vec2 pt ) +{ + return pt.x > ( pt.x - _halfWidth ) + && pt.x < ( pt.x + _halfWidth ) + && pt.y > ( pt.y - _halfHeight ) + && pt.y < ( pt.y + _halfHeight ); +} +bool Rect::isOverlap( Rect rect ) + { return this->overlap_horizontal( rect ) && this->overlap_vertical( rect ); } + + +bool Rect::overlap_horizontal( Rect rect ) +{ + return abs( this->_pt.x - rect._pt.x ) + < this->_halfWidth + rect._halfWidth; +} +bool Rect::overlap_vertical( Rect rect ) +{ + return abs( this->_pt.y - rect._pt.y ) + < this->_halfHeight + rect._halfHeight; +} + -- GitLab