I've created an SDL input manager for my 3D OpenGL applications. It's not finished yet, but I would like to know if I'm doing it the right way.
I really tried to optimise and compact my code, as it is for an OpenGL library.
InputHandler.h
#pragma once
#include <SDL2/SDL.h>
#include <vector>
#include <glm/glm.hpp>
#include "SDL_Handle.h"
#define TheInputHandler InputHandler::Instance() //Yes... Macros aren't good... but we can't ude typdef, or anything else :)
class InputHandler
{
public:
static InputHandler& Instance(){
static InputHandler instance;
return instance;
}
void Update();
inline bool ExitRequested(){ return _hasExit; }
inline glm::uvec2 GetMousePosition(){ return _mousePosition; }
inline bool KeyDown(SDL_Scancode key){
return _keyStates != 0 ? _keyStates[key] : false;
}
///disable assignemant operators
InputHandler(InputHandler const&) = delete;
InputHandler& operator=(InputHandler const&) = delete;
private:
InputHandler();/// singleton pattern
virtual ~InputHandler();
SDL_Handle _handle;
bool _hasExit = false;
glm::uvec2 _mousePosition;
const Uint8* _keyStates = nullptr;
};
InputHandler.cpp
InputHandler::InputHandler(){
_handle = SDL_Handle(); /// init SDL : uses RAII to avoid initializing twice !
}
InputHandler::~InputHandler(){}
void InputHandler::Update(){
_keyStates = SDL_GetKeyboardState(0);
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
_hasExit = true;
break;
case SDL_MOUSEMOTION:
_mousePosition = glm::uvec2(event.motion.x, event.motion.y);
break;
}
}
}