R-Type
Rect.hpp
Go to the documentation of this file.
1 /*
2 ** EPITECH PROJECT, 2023
3 ** R-Type
4 ** File description:
5 ** Rect
6 */
7 
8 #ifndef RECT_HPP_
9 #define RECT_HPP_
10 #include "RenderInterfaces.hpp"
11 #include "utils/Vector.hpp"
12 #include <SFML/Graphics/Rect.hpp>
13 #include <algorithm>
14 #include <cmath>
15 #include <iostream>
16 
17 namespace GameEngine
18 {
19  // class Circle;
20 
23  template <typename T>
24  class Rect : public IRect<T, sf::Rect>
25  {
26  public:
28  Rect() = default;
34  Rect(T l, T t, T w, T h) : left(l), top(t), width(w), height(h){};
36  ~Rect() = default;
38  T top;
41 
44  const sf::Rect<T> getBaseRect() const override { return sf::Rect<T>(left, top, width, height); };
45 
51  bool isColliding(const Vector2<T> &pos, const Rect<T> &rect, const Vector2<T> &rectPos) const
52  {
53  T posX = pos.x + left;
54  T posY = pos.y + top;
55  T rectPosX = rectPos.x + rect.left;
56  T rectPosY = rectPos.y + rect.top;
57 
58  return (posX < rectPosX + rect.width && posX + width > rectPosX && posY < rectPosY + rect.height &&
59  posY + height > rectPosY);
60  };
61 
66  void handleCollisionFromRect(Vector2<T> &pos, const Rect<T> &rect, const Vector2<T> &rectPos)
67  {
68  if (!isColliding(pos, rect, rectPos))
69  return;
70  Vector2<T> center(pos.x + (width / 2), pos.y + (height / 2));
71  Vector2<T> rectCenter(rectPos.x + (rect.width / 2), rectPos.y + (rect.height / 2));
72  T diffX = center.x - rectCenter.x;
73  T diffY = center.y - rectCenter.y;
74  if (std::abs(diffX / width) < std::abs(diffY / height)) {
75  if (diffX < 0)
76  pos.x = rectPos.x - width;
77  else
78  pos.x = rectPos.x + rect.width;
79  } else {
80  if (diffY < 0)
81  pos.y = rectPos.y - height;
82  else
83  pos.y = rectPos.y + rect.height;
84  }
85  }
86  };
87 
88  using Rectf = Rect<float>;
89  using Recti = Rect<int>;
90 
91 } // namespace GameEngine
92 
93 #endif /* !RECT_HPP_ */
Interface for rectangle.
Definition: RenderInterfaces.hpp:35
class representing a rect
Definition: Rect.hpp:25
T height
Definition: Rect.hpp:40
T top
Definition: Rect.hpp:38
Rect()=default
constructor
T left
Definition: Rect.hpp:37
const sf::Rect< T > getBaseRect() const override
get the rect stored in the class
Definition: Rect.hpp:44
~Rect()=default
destructor
void handleCollisionFromRect(Vector2< T > &pos, const Rect< T > &rect, const Vector2< T > &rectPos)
Definition: Rect.hpp:66
bool isColliding(const Vector2< T > &pos, const Rect< T > &rect, const Vector2< T > &rectPos) const
check the collision between two objects
Definition: Rect.hpp:51
T width
Definition: Rect.hpp:39
Rect(T l, T t, T w, T h)
constructor
Definition: Rect.hpp:34
a Vector2 class
Definition: Vector.hpp:20
T y
Definition: Vector.hpp:101
T x
Definition: Vector.hpp:98
@ T
Definition: Keyboard.hpp:49
Definition: AssetManager.hpp:15