Collision.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * 2D Game Engine
  3. * Collision.h:
  4. * Based on pikuma.com 2D game engine in C++ and Lua course
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 15/02/2021.
  8. */
  9. #ifndef GAMEENGINE_COLLISION_H
  10. #define GAMEENGINE_COLLISION_H
  11. #include <ECS.h>
  12. #include <Logger.h>
  13. #include <Components/Transform.h>
  14. #include <Components/BoxCollider.h>
  15. class CollisionSystem: public System
  16. {
  17. class BoxRect
  18. {
  19. double x0, y0, x1, y1;
  20. public:
  21. BoxRect(TransformComponent tc, BoxColliderComponent bc)
  22. {
  23. this->x0 = tc.position.x + bc.offset.x;
  24. this->x1 = this->x0 + bc.width;
  25. this->y0 = tc.position.y + bc.offset.y;
  26. this->y1 = this->y0 + bc.height;
  27. }
  28. bool collideWith(BoxRect &b) const
  29. {
  30. return ((this->x0 < b.x1) && (this->x1 > b.x0) && (this->y0 < b.y1) && (this->y1 > b.y0));
  31. }
  32. };
  33. public:
  34. CollisionSystem()
  35. {
  36. this->requireComponent<TransformComponent>();
  37. this->requireComponent<BoxColliderComponent>();
  38. }
  39. void update()
  40. {
  41. auto entities = this->getSystemEntities();
  42. for(auto i = entities.begin(); i != entities.end(); i++)
  43. {
  44. for(auto j = (i + 1); j != entities.end(); j++)
  45. {
  46. BoxRect boxA = BoxRect(i->getComponent<TransformComponent>(),
  47. i->getComponent<BoxColliderComponent>());
  48. BoxRect boxB = BoxRect(j->getComponent<TransformComponent>(),
  49. j->getComponent<BoxColliderComponent>());
  50. if (boxA.collideWith(boxB))
  51. {
  52. Logger::Debug("Entity #%d collided with #%d!", i->getId(), j->getId());
  53. }
  54. }
  55. }
  56. }
  57. };
  58. #endif /* GAMEENGINE_COLLISION_H */