R-Type
CollisionsUtils.hpp
Go to the documentation of this file.
1 /*
2 ** EPITECH PROJECT, 2023
3 ** R-type
4 ** File description:
5 ** CollisionsUtils
6 */
7 
8 #ifndef COLLISIONSUTILS_HPP_
9 #define COLLISIONSUTILS_HPP_
10 #include "utils/Rect.hpp"
11 
12 namespace GameEngine
13 {
14  template <typename T>
15  int replaceOnTop(Vector2<T> &pos1, const Rect<T> &rect1, const Vector2<T> &pos2, const Rect<T> &rect2)
16  {
17  if (!rect1.isColliding(pos1, rect2, pos2))
18  return -1;
19  T pos1X = pos1.x + rect1.left;
20  T pos1Y = pos1.y + rect1.top;
21  T pos2X = pos2.x + rect2.left;
22  T pos2Y = pos2.y + rect2.top;
23  T x1 = std::max(pos1X, pos2X);
24  T y1 = std::max(pos1Y, pos2Y);
25  T x2 = std::min(pos1X + rect1.width, pos2X + rect2.width);
26  T y2 = std::min(pos1Y + rect1.height, pos2Y + rect2.height);
27  Vector2<T> center(pos1X + (rect1.width / 2), pos1Y + (rect1.height / 2));
28  Vector2<T> rectCenter(pos2X + (rect2.width / 2), pos2Y + (rect2.height / 2));
29  T diffX = center.x - rectCenter.x;
30  T diffY = center.y - rectCenter.y;
31  if (x2 - x1 > y2 - y1) {
32  if (diffY < 0)
33  pos1.y = pos2Y - rect1.height - rect1.top;
34  else
35  pos1.y = pos2Y + rect2.height - rect1.top;
36  return 1;
37  } else {
38  if (diffX < 0)
39  pos1.x = pos2X - rect1.width - rect1.left;
40  else
41  pos1.x = pos2X + rect2.width - rect1.left;
42  return 0;
43  }
44  }
45 } // namespace GameEngine
46 
47 #endif /* !COLLISIONSUTILS_HPP_ */
class representing a rect
Definition: Rect.hpp:25
T height
Definition: Rect.hpp:40
T top
Definition: Rect.hpp:38
T left
Definition: Rect.hpp:37
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
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
int replaceOnTop(Vector2< T > &pos1, const Rect< T > &rect1, const Vector2< T > &pos2, const Rect< T > &rect2)
Definition: CollisionsUtils.hpp:15