Chapter 3. Input handling
- Table of Contents
- Handling Joysticks
- Handling the Keyboard
Handling Joysticks
Initialization
The first step in using a joystick in a SDL program is to initialize the Joystick subsystems of SDL. This done by passing the SDL_INIT_JOYSTICK flag to SDL_Init. The joystick flag will usually be used in conjunction with other flags (like the video flag) because the joystick is usually used to control something.
Example 3-1. Initializing SDL with Joystick Support
if (SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); }
This will attempt to start SDL with both the video and the joystick subsystems activated.
Querying
If we have reached this point then we can safely assume that the SDL library has been initialized and that the Joystick subsystem is active. We can now call some video and/or sound functions to get things going before we need the joystick. Eventually we have to make sure that there is actually a joystick to work with. It's wise to always check even if you know a joystick will be present on the system because it can also help detect when the joystick is unplugged. The function used to check for joysticks is SDL_NumJoysticks.
This function simply returns the number of joysticks available on the system. If it is at least one then we are in good shape. The next step is to determine which joystick the user wants to use. If the number of joysticks available is only one then it is safe to assume that one joystick is the one the user wants to use. SDL has a function to get the name of the joysticks as assigned by the operations system and that function is SDL_JoystickName. The joystick is specified by an index where 0 is the first joystick and the last joystick is the number returned by SDL_NumJoysticks - 1. In the demonstration a list of all available joysticks is printed to stdout.
Opening a Joystick and Receiving Joystick Events
SDL's event driven architecture makes working with joysticks a snap. Joysticks can trigger 4 different types of events:
SDL_JoyAxisEvent | Occurs when an axis changes |
SDL_JoyBallEvent | Occurs when a joystick trackball's position changes |
SDL_JoyHatEvent | Occurs when a hat's position changes |
SDL_JoyButtonEvent | Occurs when a button is pressed or released |
Events are received from all joysticks opened. The first thing that needs to be done in order to receive joystick events is to call SDL_JoystickEventState with the SDL_ENABLE flag. Next you must open the joysticks that you want to receive envents from. This is done with the SDL_JoystickOpen function. For the example we are only interested in events from the first joystick on the system, regardless of what it may be. To receive events from it we would do this:
Example 3-3. Opening a Joystick
SDL_Joystick *joystick; SDL_JoystickEventState(SDL_ENABLE); joystick = SDL_JoystickOpen(0);
If we wanted to receive events for other joysticks we would open them with calls to SDL_JoystickOpen just like we opened joystick 0, except we would store the SDL_Joystick structure they return in a different pointer. We only need the joystick pointer when we are querying the joysticks or when we are closing the joystick.
Up to this point all the code we have is used just to initialize the joysticks in order to read values at run time. All we need now is an event loop, which is something that all SDL programs should have anyway to receive the systems quit events. We must now add code to check the event loop for at least some of the above mentioned events. Let's assume our event loop looks like this:
SDL_Event event; /* Other initializtion code goes here */ /* Start main game loop here */ while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: /* handle keyboard stuff here */ break; case SDL_QUIT: /* Set whatever flags are necessary to */ /* end the main game loop here */ break; } } /* End loop here */To handle Joystick events we merely add cases for them, first we'll add axis handling code. Axis checks can get kinda of tricky because alot of the joystick events received are junk. Joystick axis have a tendency to vary just a little between polling due to the way they are designed. To compensate for this you have to set a threshold for changes and ignore the events that have'nt exceeded the threshold. 10% is usually a good threshold value. This sounds a lot more complicated than it is. Here is the Axis event handler:
Example 3-4. Joystick Axis Events
case SDL_JOYAXISMOTION: /* Handle Joystick Motion */ if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) { /* code goes here */ } break;
Another trick with axis events is that up-down and left-right movement are two different sets of axes. The most important axis is axis 0 (left-right) and axis 1 (up-down). To handle them seperatly in the code we do the following:
Example 3-5. More Joystick Axis Events
case SDL_JOYAXISMOTION: /* Handle Joystick Motion */ if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) ) { if( event.jaxis.axis == 0) { /* Left-right movement code goes here */ } if( event.jaxis.axis == 1) { /* Up-Down movement code goes here */ } } break;
Ideally the code here should use event.jaxis.value to scale something. For example lets assume you are using the joystick to control the movement of a spaceship. If the user is using an analog joystick and they push the stick a little bit they expect to move less than if they pushed it a lot. Designing your code for this situation is preferred because it makes the experience for users of analog controls better and remains the same for users of digital controls.
If your joystick has any additional axis then they may be used for other sticks or throttle controls and those axis return values too just with different event.jaxis.axis values.
Button handling is simple compared to the axis checking.
Example 3-6. Joystick Button Events
case SDL_JOYBUTTONDOWN: /* Handle Joystick Button Presses */ if ( event.jbutton.button == 0 ) { /* code goes here */ } break;
Button checks are simpler than axis checks because a button can only be pressed or not pressed. The SDL_JOYBUTTONDOWN event is triggered when a button is pressed and the SDL_JOYBUTTONUP event is fired when a button is released. We do have to know what button was pressed though, that is done by reading the event.jbutton.button field.
Lastly when we are through using our joysticks we should close them with a call to SDL_JoystickClose. To close our opened joystick 0 we would do this at the end of our program:
SDL_JoystickClose(joystick);
Advanced Joystick Functions
That takes care of the controls that you can count on being on every joystick under the sun, but there are a few extra things that SDL can support. Joyballs are next on our list, they are alot like axis with a few minor differences. Joyballs store relative changes unlike the the absolute postion stored in a axis event. Also one trackball event contains both the change in x and they change in y. Our case for it is as follows:
Example 3-7. Joystick Ball Events
case SDL_JOYBALLMOTION: /* Handle Joyball Motion */ if( event.jball.ball == 0 ) { /* ball handling */ } break;
The above checks the first joyball on the joystick. The change in position will be stored in event.jball.xrel and event.jball.yrel.
Finally we have the hat event. Hats report only the direction they are pushed in. We check hat's position with the bitmasks:
SDL_HAT_CENTERED |
SDL_HAT_UP |
SDL_HAT_RIGHT |
SDL_HAT_DOWN |
SDL_HAT_LEFT |
SDL_HAT_RIGHTUP |
SDL_HAT_RIGHTDOWN |
SDL_HAT_LEFTUP |
SDL_HAT_LEFTDOWN |
Example 3-8. Joystick Hat Events
case SDL_JOYHATMOTION: /* Handle Hat Motion */ if ( event.jhat.hat & SDL_HAT_UP ) { /* Do up stuff here */ } if ( event.jhat.hat & SDL_HAT_LEFT ) { /* Do left stuff here */ } if ( event.jhat.hat & SDL_HAT_RIGHTDOWN ) { /* Do right and down together stuff here */ } break;
In addition to the queries for number of joysticks on the system and their names there are additional functions to query the capabilities of attached joysticks:
SDL_JoystickNumAxes | Returns the number of joysitck axes |
SDL_JoystickNumButtons | Returns the number of joysitck buttons |
SDL_JoystickNumBalls | Returns the number of joysitck balls |
SDL_JoystickNumHats | Returns the number of joysitck hats |
Example 3-9. Querying Joystick Characteristics
int number_of_buttons; SDL_Joystick *joystick; joystick = SDL_JoystickOpen(0); number_of_buttons = SDL_JoystickNumButtons(joystick);
This block of code would get the number of buttons on the first joystick in the system.