I wrote a function to move the camera for my simple 3D game. I kept running into the problem where the mouse movement function for some reason triggers my Escape key, which I temporarily use to close the program, even though I didn't press it.
When I add a few more else if(event.key.keysym.sym == ...)
with other keys, it also trigger them.
Here is the code for polling event in the main game loop:
void game::userInput()
{
while(SDL_PollEvent(&event) != 0)
{
if(event.type == SDL_QUIT)
{
cout << "quit";
running = false;
}
else if(event.key.keysym.sym == SDLK_ESCAPE)
{
cout << event.key.keysym.sym << endl;
running = false;
}
else
{
square->input_mouse(event);
}
}
}
Here is the code for taking mouse input
void input_mouse(SDL_Event event)
{
float mouse_sensitivity = 0.001;
if(event.type == SDL_MOUSEMOTION)
{
int mxo = event.motion.xrel;
if(mxo < 0)
{
cout << "Looking left" << endl;
}
else if(mxo > 0)
{
cout << "Looking right" << endl;
}
}
}
You have to check that event.type
is SDL_KEYDOWN
or SDL_KEYUP
before accessing event.key.*
, similar to how you're checking for SDL_MOUSEMOTION
in input_mouse()
.