- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 374字
- 2021-08-27 18:31:13
Time for action - Handling gamepad events
Let's start with adding the Qt Gamepad add-on to our project by editing the jrgame.pro file:
QT += core gui widgets gamepad
This will make the headers of the library available to our project and tell qmake to link the project against this library. Now add the following code to the constructor of the MyScene class:
QList<int> gamepadIds = QGamepadManager::instance()->connectedGamepads(); if (!gamepadIds.isEmpty()) { QGamepad *gamepad = new QGamepad(gamepadIds[0], this); connect(gamepad, &QGamepad::axisLeftXChanged, this, &MyScene::axisLeftXChanged); connect(gamepad, &QGamepad::axisLeftYChanged, this, &MyScene::axisLeftYChanged); }
The code is pretty straightforward. First, we use
QGamepadManager::connectedGamepads to get the list of IDs of the available gamepads. If some gamepads were found, we create a QGamepad object for the first found gamepad. We pass this to its constructor, so it becomes a child of our MyScene object, and we don't need to worry about deleting it. Finally, we connect the gamepad's axisLeftXChanged() and axisLeftYChanged() signals to new slots in the MyScene class. Now, let's implement these slots:
void MyScene::axisLeftXChanged(double value) { int direction; if (value > 0) { direction = 1; } else if (value < 0) { direction = -1; } else { direction = 0; } m_player->setDirection(direction); checkTimer(); } void MyScene::axisLeftYChanged(double value)
{
if (value < -0.25) {
jump();
}
}
The value argument of the signals contains a number from -1 to 1. It allows us not
only to detect whether a thumbstick was pressed, but also to get more precise information
about its position. However, in our simple game, we don't need this precision. In the axisLeftXChanged() slot, we calculate and set the elephant's direction based on the sign of the received value. In the axisLeftYChanged() slot, if we receive a large enough negative value, we interpret it as a jump command. This will help us avoid accidental jumps. That's all! Our game now supports both keyboards and gamepads.