Space Fighter
A "shmup" game for Computer Programming C++
Loading...
Searching...
No Matches
CollisionManager.cpp
Go to the documentation of this file.
1
2#include "CollisionManager.h"
3
4
6{
7 Collision c;
8 c.Type1 = (type1 < type2) ? type1 : type2;
9 c.Type2 = (type1 > type2) ? type1 : type2;
10 c.Callback = callback;
11
12 m_collisions.push_back(c);
13}
14
15void CollisionManager::CheckCollision(GameObject *pGameObject1, GameObject *pGameObject2)
16{
17 CollisionType t1 = pGameObject1->GetCollisionType();
18 CollisionType t2 = pGameObject2->GetCollisionType();
19
20 if (t1 == t2 || t1 == CollisionType::None || t2 == CollisionType::None) return;
21
22 bool swapped = false;
23 if (t1 > t2)
24 {
25 std::swap(t1, t2);
26 swapped = true;
27 }
28
29 m_nonCollisionIt = m_nonCollisions.begin();
30 for (; m_nonCollisionIt != m_nonCollisions.end(); m_nonCollisionIt++)
31 {
32 NonCollision nc = *m_nonCollisionIt;
33 if ((nc.Type1 == t1 && nc.Type2 == t2)) return;
34 }
35
36 m_collisionIt = m_collisions.begin();
37 for (; m_collisionIt != m_collisions.end(); m_collisionIt++)
38 {
39 Collision c = *m_collisionIt;
40 if ((c.Type1 == t1 && c.Type2 == t2))
41 {
42 Vector2 difference = pGameObject1->GetPosition() - pGameObject2->GetPosition();
43
44 float radiiSum = pGameObject1->GetCollisionRadius() + pGameObject2->GetCollisionRadius();
45 float radiiSumSquared = radiiSum * radiiSum;
46
47 if (difference.LengthSquared() <= radiiSumSquared)
48 {
49 if (!swapped) c.Callback(pGameObject1, pGameObject2);
50 else c.Callback(pGameObject2, pGameObject1);
51 }
52 return;
53 }
54 }
55
56 AddNonCollisionType(t1, t2);
57}
58
60{
61 NonCollision nc;
62 nc.Type1 = (type1 < type2) ? type1 : type2;
63 nc.Type2 = (type1 > type2) ? type1 : type2;
64 m_nonCollisions.push_back(nc);
65}
void(* OnCollision)(GameObject *pGameObject1, GameObject *pGameObject2)
virtual void CheckCollision(GameObject *pGameObject1, GameObject *pGameObject2)
Check for collisions between game objects.
virtual void AddNonCollisionType(const CollisionType type1, const CollisionType type2)
Add a non-collision type to the manager.
virtual void AddCollisionType(const CollisionType type1, const CollisionType type2, OnCollision callback)
Add a collision type to the manager.
Represents a type of collision.
static const CollisionType None
Represents a game object in the game. This is the base class for all objects that can be updated,...
Definition GameObject.h:15
virtual CollisionType GetCollisionType() const =0
Get the collision type of the object.
virtual float GetCollisionRadius() const
Get the collision radius of the object.
Definition GameObject.h:80
virtual Vector2 & GetPosition()
Get the position of the object.
Definition GameObject.h:52
Defines a vector with 2 components (x and y).
Definition Vector2.h:21
float LengthSquared() const
Calculates the length of the vector squared.
Definition Vector2.cpp:30