From 29baefe85ac8a0a1c33fd265459a3c72c4557943 Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Mon, 15 Jan 2018 21:40:53 -0500 Subject: [PATCH] handle controller axis events --- sdl-game-controller.cc | 48 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/sdl-game-controller.cc b/sdl-game-controller.cc index 2b960c5..8849aed 100644 --- a/sdl-game-controller.cc +++ b/sdl-game-controller.cc @@ -28,6 +28,14 @@ GLfloat colors[][4] = { {1.0, 1.0, 0.0, 1.0}, {0.2, 0.2, 1.0, 1.0}, }; +float movement[2]; +static SDL_Event UpdateEvent; + +static Uint32 UpdateCallback(Uint32 interval, void * param) +{ + SDL_PushEvent(&UpdateEvent); + return interval; +} bool init(void) { @@ -77,9 +85,26 @@ void display(SDL_Window * window) SDL_GL_SwapWindow(window); } +void process_movement(int axis, float amount) +{ + position[axis] += amount; + if (position[axis] < -1.0) + position[axis] = -1.0; + else if (position[axis] > 1.0) + position[axis] = 1.0; +} + +void process_movements() +{ + for (int i = 0; i <= 1; i++) + { + process_movement(i, movement[i] * 25.0 / 1000.0); + } +} + int main(int argc, char *argv[]) { - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS)) + if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS)) { printf("Failed to initialize SDL!\n"); return 1; @@ -119,6 +144,10 @@ int main(int argc, char *argv[]) return 2; } + UpdateEvent.type = SDL_USEREVENT; + UpdateEvent.user.code = 0; + SDL_AddTimer(25, UpdateCallback, NULL); + int n_joysticks = SDL_NumJoysticks(); std::list game_controllers; for (int i = 0; i < n_joysticks; i++) @@ -152,12 +181,27 @@ int main(int argc, char *argv[]) } else if (event.type == SDL_CONTROLLERAXISMOTION) { - std::cerr << "motion!" << std::endl; + if (event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX) + { + movement[0] = event.caxis.value / 32768.0; + if (fabsf(movement[0]) < 0.02) + movement[0] = 0.0; + } + else if (event.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY) + { + movement[1] = -event.caxis.value / 32768.0; + if (fabsf(movement[1]) < 0.02) + movement[1] = 0.0; + } } else if (event.type == SDL_CONTROLLERBUTTONDOWN) { std::cerr << "button!" << std::endl; } + else if (event.type == SDL_USEREVENT) + { + process_movements(); + } } if (exit) break;