GameKit  0.0.1a
C++ gamedev tools
CollisionHelper.cpp
Go to the documentation of this file.
1 /*
2  * =====================================================================================
3  *
4  * Filename: CollisionHelper.cpp
5  *
6  * Description:
7  *
8  * Created: 17/01/2018 19:39:36
9  *
10  * Author: Quentin Bazin, <quent42340@gmail.com>
11  *
12  * =====================================================================================
13  */
15 
20 
21 namespace gk {
22 
24  bool collision = inCollision(object1, object2);
25 
26  if(object1.has<CollisionComponent>()) {
27  object1.get<CollisionComponent>().collisionActions(object1, object2, collision);
28  }
29 
30  if(object2.has<CollisionComponent>()) {
31  object2.get<CollisionComponent>().collisionActions(object2, object1, collision);
32  }
33 }
34 
36  if(object1.has<PositionComponent>() && object1.has<HitboxComponent>()
37  && object2.has<PositionComponent>() && object2.has<HitboxComponent>()) {
38  auto &hitbox1 = object1.get<HitboxComponent>();
39  auto &hitbox2 = object2.get<HitboxComponent>();
40 
41  if(hitbox1.currentHitbox() && hitbox2.currentHitbox()) {
42  FloatRect rect1 = *hitbox1.currentHitbox();
43  FloatRect rect2 = *hitbox2.currentHitbox();
44 
45  auto &pos1 = object1.get<PositionComponent>();
46  auto &pos2 = object2.get<PositionComponent>();
47 
48  rect1.x += pos1.x;
49  rect1.y += pos1.y;
50 
51  rect2.x += pos2.x;
52  rect2.y += pos2.y;
53 
54  if(object1.has<MovementComponent>()) {
55  auto &movement = object1.get<MovementComponent>();
56  rect1.x += movement.v.x;
57  rect1.y += movement.v.y;
58  }
59 
60  if(object2.has<MovementComponent>()) {
61  auto &movement = object2.get<MovementComponent>();
62  rect2.x += movement.v.x;
63  rect2.x += movement.v.y;
64  }
65 
66  if(rect1.intersects(rect2)) {
67  return true;
68  }
69  }
70  }
71 
72  return false;
73 }
74 
75 } // namespace gk
76 
void checkCollision(SceneObject &object1, SceneObject &object2)
const FloatRect * currentHitbox() const
T & get() const
Definition: SceneObject.hpp:42
T y
Top coordinate of the rectangle.
Definition: Rect.hpp:216
bool has() const
Definition: SceneObject.hpp:37
T x
Left coordinate of the rectangle.
Definition: Rect.hpp:215
bool intersects(const Rect< T > &rect) const
Check the intersection between two rectangles.
Definition: Rect.hpp:132
virtual bool inCollision(SceneObject &object1, SceneObject &object2)