Search code examples
c++controllersdlxbox

SDL Joystick Button Pressed / C++


How Can I recognize if a certain Button on a Controller is pressed or not ? For Example the A Button on the Xbox 360 Controller...


Solution

  • You first have to have had initialized SDL's joystick support (I'm assuming SDL2 here, but lower versions shouldn't be that different.) Like so:

    SDL_InitSubSystem(SDL_INIT_JOYSTICK);  // bitwise OR with other subsystems you need,
                                           // e.g. SDL_INIT_VIDEO | SDL_INIT_JOYSTICK
    

    Then you have to open a given joystick (usually, you enumerate all joysticks and let the user choose one or pick one for them.) Like so:

    SDL_Joystick * joy = SDL_JoystickOpen(0);  // Use 1, 2, etc. for the other joysticks,
                                               // You should use SDL_NumJoysticks() then.
    

    And don't forget to "close" the joystick when you are done with it (SDL_JoystickClose(joy).)

    Anyways, when you have done all these (typically only once, and outside of your game loop,) then you check the button you are interested in like this:

    if (SDL_JoystickGetButton(joy, button_number) != 0)
        // Button was pressed; yay!
    

    To figure out the number of the button, you can do some experiments. IIRC, the Xbox360 controller's buttons and axes stay at the same numbers pretty much always.

    Note that SDL also has the "game controller" API which is closely related to the ones above; just use GameController instead of Joystick in the function names.