I'm working on an entity component based game and I ran into this problem. I've got a component called PlayerControlComponent:
void PlayerControlComponent::HandleInput() {
SDL_Event event;
while(SDL_PollEvent(&event) != 0) {
if(event.key.keysym.sym == SDLK_RIGHT) {
Entity->MoveRight();
}
else if(event.key.keysym.sym == SDLK_RIGHT) {
Entity->MoveLeft();
}
else {
Entity->Stay();
}
}
}
and I've got a GameManager class that handles the input for the window, like if you hit escape it will quit:
void GameManager::HandleInput() {
SDL_Event event;
while(SDL_PollEvent(&event) != 0) {
switch(event.key.keysym.sym) {
case SDL_QUIT:
case SDLK_ESCAPE:
Quit();
}
}
}
After I put everything in my main function, it looks like this:
while(GameManager::GetInstance().IsRunning()) {
//Inputs
GameManager::GetInstance().HandleInput();
player->GetComponent<PlayerControlComponent>()->HandleInput();
//Update, Draw, etc..
My problem is that wich ever I put first gets executed only. So in this example the player won't handle inputs. If change it up and put the player first like so:
while(GameManager::GetInstance().IsRunning()) {
//Inputs
player->GetComponent<PlayerControlComponent>()->HandleInput();
GameManager::GetInstance().HandleInput();
//Update, Draw, etc..
..my player will move but than the window won't quit if I hit escape. For some reason wich ever input handling function is called first, gets executed. I figured out it has something to do with SDL_PollEvent()
. So I created a global SDL_Event variable and changed up the code a bit so there is only 1 SDL_PollEvent()
call wich happens in main:
while(GameManager::GetInstance().IsRunning()) {
//Inputs
while(SDL_PollEvent(&event) != 0) {
GameManager::GetInstance().HandleInput();
player->GetComponent<PlayerControlComponent>()->HandleInput();
}
//Update, Drawing, etc..
So as I said, the event
variable is now global and both GameManager
and Player
uses the (only) same event
variable.b Now everything works fine, but is that really the only option? (If so, than I don't know why would they allow us to declare multiple SDL_Event
s.)
So my question is:
Is there a way around this, can I handle multiple input events?