So I've got this code:
void Engine::Run() {
// initialize all components
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK))
throw Exception("couldn't initialize SDL\n" + string(SDL_GetError()), 1);
// other code
run = true;
SDL_Event event;
while (run) {
// other code
uint32 timeout = SDL_GetTicks() + 50;
while (SDL_PollEvent(&event) && timeout - SDL_GetTicks() > 0)
HandleEvent(event);
}
}
void Engine::HandleEvent(const SDL_Event& event) {
switch (event.type) {
case SDL_KEYDOWN:
inputSys->KeyDownEvent(event.key);
break;
case SDL_KEYUP:
inputSys->KeyUpEvent(event.key);
break;
case SDL_JOYBUTTONDOWN:
cout << "button" << endl;
break;
case SDL_JOYHATMOTION:
cout << "hat" << endl;
break;
case SDL_JOYAXISMOTION:
cout << "axis" << endl;
break;
case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED:
inputSys->UpdateControllers();
break;
// other code
}
}
The problem is that the only events that aren't being called, are the joystick button, hat and axis events. The other two joystick related events work just fine.
I'm using the exact same code in a different project, where all joystick events get called without issue, but since I moved the code to my new project, they don't get called anymore.
SDL does recognize the plugged in controller and I can use functions like SDL_JoystickGetAxis, but for some reason these three events don't seem to be working. Any idea why that is?
You have to call SDL_JoystickOpen to get those events. Here's their example:
SDL_Joystick *joy;
// Initialize the joystick subsystem
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
// Check for joystick
if (SDL_NumJoysticks() > 0) {
// Open joystick
joy = SDL_JoystickOpen(0);
if (joy) {
printf("Opened Joystick 0\n");
printf("Name: %s\n", SDL_JoystickNameForIndex(0));
printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joy));
printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joy));
printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
} else {
printf("Couldn't open Joystick 0\n");
}
// Close if opened
if (SDL_JoystickGetAttached(joy)) {
SDL_JoystickClose(joy);
}
}