123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- /*
- * 2D Game Engine
- * KeyboardMovement.h:
- * Based on pikuma.com 2D game engine in C++ and Lua course
- * Copyright (c) 2021 986-Studio. All rights reserved.
- *
- * Created by Manoël Trapier on 16/02/2021.
- */
- #ifndef GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H
- #define GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H
- #include <SDL.h>
- #include <ECS.h>
- #include <EventBus.h>
- #include <Events/KeyPressed.h>
- #include <Components/Sprite.h>
- #include <Components/KeyboardControl.h>
- #include <Components/RigidBody.h>
- class KeyboardMovementSystem : public System
- {
- public:
- KeyboardMovementSystem()
- {
- this->requireComponent<KeyboardControlComponent>();
- this->requireComponent<SpriteComponent>();
- this->requireComponent<RigidBodyComponent>();
- }
- void subscriptToEvents(std::unique_ptr<EventBus> &eventBus)
- {
- eventBus->subscribeToEvent<KeyPressedEvent>(this, &KeyboardMovementSystem::onKeyPressed);
- }
- void onKeyPressed(KeyPressedEvent &event)
- {
- for(auto entity: this->getSystemEntities())
- {
- auto keyboardControl = entity.getComponent<KeyboardControlComponent>();
- auto &sprite = entity.getComponent<SpriteComponent>();
- auto &rigitBody = entity.getComponent<RigidBodyComponent>();
- switch(event.keyCode)
- {
- case SDLK_UP:
- rigitBody.velocity = keyboardControl.upVelocity;
- sprite.sourceRect.y = sprite.height * 0;
- break;
- case SDLK_RIGHT:
- rigitBody.velocity = keyboardControl.rightVelocity;
- sprite.sourceRect.y = sprite.height * 1;
- break;
- case SDLK_DOWN:
- rigitBody.velocity = keyboardControl.downVelocity;
- sprite.sourceRect.y = sprite.height * 2;
- break;
- case SDLK_LEFT:
- rigitBody.velocity = keyboardControl.leftVelocity;
- sprite.sourceRect.y = sprite.height * 3;
- break;
- default:
- /* Ignore all other keys */
- break;
- }
- }
- }
- void Update()
- {
- }
- };
- #endif /* GAMEENGINE_SOURCE_INCLUDE_SYSTEMS_KEYBOARDMOVEMENT_H */
|