0
0
mirror of https://github.com/Nimac0/SDL_Minigame synced 2026-01-12 09:03:42 +00:00

added InputSystemComponent

needs testing
This commit is contained in:
Sara Varga 2024-06-21 22:47:36 +02:00
parent e71fcbf9e5
commit cefa1c2e29
4 changed files with 84 additions and 2 deletions

View File

@ -1,4 +1,5 @@
#pragma once
#include <SDL.h>
#include <map>

View File

@ -0,0 +1,28 @@
#pragma once
#include <map>
#include <vector>
#include <functional>
#include "Component.h"
#include "InputComponent.h"
#include "InputAction.h"
class InputSystemComponent : public InputComponent {
public:
InputSystemComponent() = default;
~InputSystemComponent() = default;
void init() override;
void update() override;
void bindAction(const std::string& actionName, Key key, std::function<void()> callback);
void unbindAction(const std::string& actionName, Key key);
private:
InputComponent* m_inputComponent;
std::map<Key, std::vector<InputAction>> m_keyToActionsMap;
std::map<std::string, InputAction> m_actions;
void handleActions();
};

View File

@ -10,8 +10,7 @@ InputComponent::~InputComponent() = default;
void InputComponent::init()
{
// m_keyStates = SDL_GetKeyboardState(NULL);
// InitKeyMappings();
// function intentionally left empty
}
void InputComponent::update()

View File

@ -0,0 +1,54 @@
#include "InputSystemComponent.h"
void InputSystemComponent::init()
{
InputComponent::init();
}
void InputSystemComponent::update()
{
InputComponent::update();
handleActions();
}
void InputSystemComponent::bindAction(const std::string& actionName, Key key, std::function<void()> callback)
{
if (m_actions.find(actionName) == m_actions.end())
{
m_actions[actionName] = InputAction(actionName, callback);
}
m_actions[actionName].keys.push_back(key);
m_keyToActionsMap[key].push_back(m_actions[actionName]);
}
void InputSystemComponent::unbindAction(const std::string& actionName, Key key)
{
auto actionIt = m_actions.find(actionName);
if (actionIt != m_actions.end())
{
auto& action = actionIt->second;
action.keys.erase(std::remove(action.keys.begin(), action.keys.end(), key), action.keys.end());
m_keyToActionsMap[key].erase(std::remove_if(m_keyToActionsMap[key].begin(), m_keyToActionsMap[key].end(),
[&](const InputAction& a) { return a.name == actionName; }), m_keyToActionsMap[key].end());
}
}
void InputSystemComponent::handleActions()
{
for (auto& keyActionsPair : m_keyToActionsMap)
{
Key key = keyActionsPair.first;
if (isKeyDown(key))
{
for (auto& action : keyActionsPair.second)
{
if (action.callback)
{
action.callback();
}
}
}
}
}