I am making a C++, SDL based, game engine, and I need help to finish it and polish it.…
- User
I am making a C++, SDL based, game engine, and I need help to finish it and polish it. Currently I am doing the final touches to my InputManager class, check if it is correct or if something is missing or could be improved:
class InputManager { public: ~InputManager() = default; InputManager(const InputManager&) = delete; InputManager operator=(const InputManager&) = delete; static InputManager& GetInstance(); void Update(); bool IsKeyPressed(Input::KeyCode key) const; bool IsKeyReleased(Input::KeyCode key) const; bool IsMouseButtonPressed(Input::MouseButton button) const; Point GetMousePosition() const; bool IsGamepadButtonDown(Input::GamepadButton button, int gamepadIndex) const;
private: InputManager(); void KeyPressed(uint8_t keyPressed); void KeyReleased(uint8_t keyReleased); void SetMouseState(uint8_t mouseButton, bool pressed); SDL_GameController* GetGamepad(); std::unordered_map<Input::KeyCode, bool> currentKeyboardState; std::unordered_map<Input::KeyCode, bool> previousKeyboardState; std::unordered_map<Input::MouseButton, bool> mouseButtonsState; SDL_GameController* gamepad;};
#include "InputManager.h"
#include #include
uint8_t KeyToSDL(Input::KeyCode keyCode); Input::KeyCode KeyFromSDL(uint8_t sdlKeyCode); uint8_t MouseButtonToSDL(Input::MouseButton mouseButton); Input::MouseButton MouseButtonFromSDL(uint8_t sdlMouseButton); SDL_GameControllerButton GamepadButtonToSDL(Input::GamepadButton gamepadButton); Input::GamepadButton GamepadButtonFromSDL(SDL_GameControllerButton sdlGamepadButton);
InputManager::InputManager() { }
InputManager& InputManager::GetInstance() { static InputManager instance;
return instance;}
void InputManager::Update() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { KeyPressed(event.key.keysym.sym); break; } case SDL_KEYUP: { KeyReleased(event.key.keysym.sym); break; } case SDL_MOUSEBUTTONUP: { SetMouseState(event.button.button, false); break; } case SDL_MOUSEBUTTONDOWN: { SetMouseState(event.button.button, true); break; } case SDL_CONTROLLERDEVICEADDED: { if (!gamepad) { gamepad = SDL_GameControllerOpen(event.cdevice.which); } break; } case SDL_CONTROLLERDEVICEREMOVED: { if (gamepad && event.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamepad))) { SDL_GameControllerClose(gamepad); gamepad = GetGamepad(); } break; } } } }
bool InputManager::IsKeyPressed(Input::KeyCode key) const { return currentKeyboardState.at(key) && !previousKeyboardState.at(key); }
bool InputManager::IsKeyReleased(Input::KeyCode key) const { return !currentKeyboardState.at(key) && previousKeyboardState.at(key); }
bool InputManager::IsMouseButtonPressed(Input::MouseButton button) const { return mouseButtonsState.at(button); }
Point InputManager::GetMousePosition() const { int x = 0; int y = 0; SDL_GetMouseState(&x, &y);
return Point(x, y);}
bool InputManager::IsGamepadButtonDown(Input::GamepadButton button, int gamepadIndex) const { return SDL_GameControllerGetButton(gamepad, GamepadButtonToSDL(button)); }
void InputManager::KeyPressed(uint8_t keyPressed) { previousKeyboardState.at(KeyFromSDL(keyPressed)) = false; currentKeyboardState.at(KeyFromSDL(keyPressed)) = true; }
void InputManager::KeyReleased(uint8_t keyReleased) { previousKeyboardState.at(KeyFromSDL(keyReleased)) = true; currentKeyboardState.at(KeyFromSDL(keyReleased)) = false; }
void InputManager::SetMouseState(uint8_t mouseButton, bool pressed) { mouseButtonsState[MouseButtonFromSDL(mouseButton)] = pressed; }
SDL_GameController* InputManager::GetGamepad() { for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { return SDL_GameControllerOpen(i); } }
return nullptr;}
- Assistant
Your
InputManagerclass is well structured with clear intent for each function. Here's some feedback and suggestions for improvement:-
Thread Safety: If your game engine is expected to be run on multiple threads, it's important to ensure that your
InputManageris thread-safe. Data shared between threads, like the input states, should be carefully managed to prevent race conditions. -
Exception Handling: Your code currently uses
std::unordered_map::atwhich throws an exception if the key is not found. It's often a good idea, especially in a real-time system such as a game, to avoid exceptions and instead handle such cases manually, maybe by returning a default value or an error code. -
Previous State Updating: It looks like you might have a bug in your
KeyPressedandKeyReleasedmethods. You setpreviousKeyboardState.at(KeyFromSDL(keyPressed))tofalsewhen a key is pressed. However,previousKeyboardStateshould usually represent the state of the keys during the last frame, not get updated immediately when a new event comes in. The code to updatepreviousKeyboardStateshould probably be in theUpdatemethod, called once per frame before processing new events. -
Return Value of
IsGamepadButtonDown: The methodIsGamepadButtonDownalways gets the state fromgamepad, disregarding thegamepadIndexparameter. This might be a bug if you intend to support multiple gamepads. Make sure to access the correct gamepad according to the given index. -
Initialization of
gamepadPointer: Yourgamepadpointer is used but never initialized in the constructor. This could potentially lead to undefined behavior. Consider initializing it tonullptrin the constructor. -
Mouse Buttons State Updating: The
SetMouseStatemethod will insert new keys into themouseButtonsStatemap, but there's no code showing where the initial state is set. Ensure that the state is properly initialized before use. -
Make sure to add the necessary
#includestatements for any types or functions you're using in the header file, such as<unordered_map>forstd::unordered_map,<utility>forstd::pairif you're usingPoint, the correct includes for SDL, and any that provideInput::KeyCode,Input::MouseButton, andInput::GamepadButtondefinitions. -
Event Loop Inside
Update: TheUpdatemethod polls all SDL events, including potentially non-input related ones. This is usually fine for small projects, but for larger applications, you might want to have a dedicated event manager that dispatches events to different systems accordingly. -
Singleton Pattern: You are using the singleton pattern for your
InputManager. This pattern can sometimes lead to issues with unit testing and refactoring, and it can also make dependencies less clear. Consider if passing an instance ofInputManagerto objects that need it (dependency injection) might be a better option depending on your architecture. -
Destructor: The
~InputManager()destructor does not clean up thegamepadif it's open. It's a good idea to ensure that resources are properly released if they are acquired.
Here's one possible approach for safely updating the keyboard state:
void InputManager::UpdateState() { previousKeyboardState = currentKeyboardState; SDL_Event event; // ... (handle events) }In your update loop,
UpdateStatewould be called once per frame, ensuring thatpreviousKeyboardStateis the keyboard state from the last frame.Lastly, whenever dealing with raw pointers, especially with external resources like SDL's
SDL_GameController, it's beneficial to consider smart pointers, such asunique_ptrwith a custom deleter, to handle the resource management more safely and conveniently. -