handle controller axis events

This commit is contained in:
Josh Holtrop 2018-01-15 21:40:53 -05:00
parent 0fffdfb38f
commit 29baefe85a

View File

@ -28,6 +28,14 @@ GLfloat colors[][4] = {
{1.0, 1.0, 0.0, 1.0}, {1.0, 1.0, 0.0, 1.0},
{0.2, 0.2, 1.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) bool init(void)
{ {
@ -77,9 +85,26 @@ void display(SDL_Window * window)
SDL_GL_SwapWindow(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[]) 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"); printf("Failed to initialize SDL!\n");
return 1; return 1;
@ -119,6 +144,10 @@ int main(int argc, char *argv[])
return 2; return 2;
} }
UpdateEvent.type = SDL_USEREVENT;
UpdateEvent.user.code = 0;
SDL_AddTimer(25, UpdateCallback, NULL);
int n_joysticks = SDL_NumJoysticks(); int n_joysticks = SDL_NumJoysticks();
std::list<SDL_GameController *> game_controllers; std::list<SDL_GameController *> game_controllers;
for (int i = 0; i < n_joysticks; i++) for (int i = 0; i < n_joysticks; i++)
@ -152,12 +181,27 @@ int main(int argc, char *argv[])
} }
else if (event.type == SDL_CONTROLLERAXISMOTION) 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) else if (event.type == SDL_CONTROLLERBUTTONDOWN)
{ {
std::cerr << "button!" << std::endl; std::cerr << "button!" << std::endl;
} }
else if (event.type == SDL_USEREVENT)
{
process_movements();
}
} }
if (exit) if (exit)
break; break;