Hello,
In my game I have a input-manager class, that can check for an keyboard input. Sadly at the moment it only works for one input at the time, but I want it to work for multiple (e.g. press STRG + m, then something will happen)
I don't know, what changes I have to do on my existing class, or even if it works...
I would highly appreciate it, if you could say that to me :)
Here is my Code:
InputManager.h:
#pragma once
#include <unordered_map>
#include <glm/glm.hpp>
namespace Bengine {
// Input manager stores a key map that maps SDL_Keys to booleans.
// If the value in the key map is true, then the key is pressed.
// Otherwise, it is released.
class InputManager
{
public:
InputManager();
~InputManager();
void update();
void pressKey(unsigned int keyID);
void releaseKey(unsigned int keyID);
void setMouseCoords(float x, float y);
/// Returns true if the key is held down
bool isKeyDown(unsigned int keyID);
/// Returns true if the key was just pressed
bool isKeyPressed(unsigned int keyID);
//getters
glm::vec2 getMouseCoords() const { return _mouseCoords; }
private:
/// Returns true if the key is held down
bool wasKeyDown(unsigned int keyID);
std::unordered_map<unsigned int, bool> _keyMap;
std::unordered_map<unsigned int, bool> _previousKeyMap;
glm::vec2 _mouseCoords;
};
}
InputManager.cpp:
#include "InputManager.h"
namespace Bengine {
InputManager::InputManager() : _mouseCoords(0.0f)
{
}
InputManager::~InputManager()
{
}
void InputManager::update() {
// Loop through _keyMap using a for each loop, and copy it over to _previousKeyMap
for (auto& it : _keyMap) {
_previousKeyMap[it.first] = it.second;
}
}
void InputManager::pressKey(unsigned int keyID) {
// Here we are treating _keyMap as an associative array.
// if keyID doesn't already exist in _keyMap, it will get added
_keyMap[keyID] = true;
}
void InputManager::releaseKey(unsigned int keyID) {
_keyMap[keyID] = false;
}
void InputManager::setMouseCoords(float x, float y) {
_mouseCoords.x = x;
_mouseCoords.y = y;
}
bool InputManager::isKeyDown(unsigned int keyID) {
// We dont want to use the associative array approach here
// because we don't want to create a key if it doesnt exist.
// So we do it manually
auto it = _keyMap.find(keyID);
if (it != _keyMap.end()) {
// Found the key
return it->second;
} else {
// Didn't find the key
return false;
}
}
bool InputManager::isKeyPressed(unsigned int keyID) {
// Check if it is pressed this frame, and wasn't pressed last frame
if (isKeyDown(keyID) == true && wasKeyDown(keyID) == false) {
return true;
}
return false;
}
bool InputManager::wasKeyDown(unsigned int keyID) {
// We dont want to use the associative array approach here
// because we don't want to create a key if it doesnt exist.
// So we do it manually
auto it = _previousKeyMap.find(keyID);
if (it != _previousKeyMap.end()) {
// Found the key
return it->second;
} else {
// Didn't find the key
return false;
}
}
}