KeyboardMovement.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * 2D Game Engine
  3. * KeyboardMovement.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 16/02/2021.
  8. */
  9. #ifndef GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H
  10. #define GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H
  11. #include <SDL.h>
  12. #include <ECS.h>
  13. #include <EventBus.h>
  14. #include <Events/KeyPressed.h>
  15. #include <Components/Sprite.h>
  16. #include <Components/KeyboardControl.h>
  17. #include <Components/RigidBody.h>
  18. class KeyboardMovementSystem : public System
  19. {
  20. public:
  21. KeyboardMovementSystem()
  22. {
  23. this->requireComponent<KeyboardControlComponent>();
  24. this->requireComponent<SpriteComponent>();
  25. this->requireComponent<RigidBodyComponent>();
  26. }
  27. void subscriptToEvents(std::unique_ptr<EventBus> &eventBus)
  28. {
  29. eventBus->subscribeToEvent<KeyPressedEvent>(this, &KeyboardMovementSystem::onKeyPressed);
  30. }
  31. void onKeyPressed(KeyPressedEvent &event)
  32. {
  33. for(auto entity: this->getSystemEntities())
  34. {
  35. auto keyboardControl = entity.getComponent<KeyboardControlComponent>();
  36. auto &sprite = entity.getComponent<SpriteComponent>();
  37. auto &rigitBody = entity.getComponent<RigidBodyComponent>();
  38. switch(event.keyCode)
  39. {
  40. case SDLK_UP:
  41. rigitBody.velocity = keyboardControl.upVelocity;
  42. sprite.sourceRect.y = sprite.height * 0;
  43. break;
  44. case SDLK_RIGHT:
  45. rigitBody.velocity = keyboardControl.rightVelocity;
  46. sprite.sourceRect.y = sprite.height * 1;
  47. break;
  48. case SDLK_DOWN:
  49. rigitBody.velocity = keyboardControl.downVelocity;
  50. sprite.sourceRect.y = sprite.height * 2;
  51. break;
  52. case SDLK_LEFT:
  53. rigitBody.velocity = keyboardControl.leftVelocity;
  54. sprite.sourceRect.y = sprite.height * 3;
  55. break;
  56. default:
  57. /* Ignore all other keys */
  58. break;
  59. }
  60. }
  61. }
  62. void Update()
  63. {
  64. }
  65. };
  66. #endif /* GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H */