- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 377字
- 2021-08-27 18:31:13
Working with gamepads in Qt
The starting point of the gamepad API is the QGamepadManager class. The singleton object of this class can be obtained using the QGamepadManager::instance() function. It allows you to request the list of identifiers of the available gamepads using the connectedGamepads() function. The gamepadConnected() signal can be used to detect new gamepads on the fly. QGamepadManager also provides API for configuring buttons and axes on the gamepad and is able to save the configuration to the specified settings file.
After you detected that one or multiple gamepads are available in the system, you should create a new QGamepad object and pass the obtained device identifier as a constructor's argument. You can use the first available gamepad or allow the user to select which gamepad to use. In this case, you can utilize the gamepad's name property that returns a readable name of the device.
The Gamepad object contains a dedicated property for each axis and button. This gives you two ways to receive the information about the state of the controls. First, you can use the getter of the property to check the current state of a button or an axis. For example, the buttonL1() function will return true if the L1 button is currently pressed, and the axisLeftX() will return the current horizontal position of the left stick as a double value that is in the range of -1 to 1. For trigger buttons (for example, buttonL2()), the property contains a double value that ranges from 0 (not pressed) to 1 (fully pressed).
The second way is to use the signals corresponding to each property. For example, you can connect to the gamepad's buttonL1Changed(bool value) and axisLeftXChanged(double value) signals to monitor the changes of the corresponding properties.
Finally, the QGamepadKeyNavigation class can be used to quickly add gamepad support to a keyboard-oriented application. When you create an object of this class, your application will begin receiving key events caused by gamepads. By default, GamepadKeyNavigation will emulate up, down, left, right, back, forward, and return keys when the corresponding gamepad buttons are pressed. However, you can override the default mapping or add your own mapping for other gamepad buttons.