How to do it…

To move an object using keyboard controls, follow these steps:

  1. Open up renderwindow.h and declare two floating-point numbers called moveX and moveZ. Then, declare a QVector3D variable called movement:
QTime* time;
int currentTime = 0;
int oldTime = 0;
float deltaTime = 0;
float rotation = 0;
float moveX = 0;
float moveZ = 0;
QVector3D movement = QVector3D(0, 0, 0);

  1. We will also declare two functions called keyPressEvent() and keyReleaseEvent():
protected:
void initializeGL();
void paintEvent(QPaintEvent *event);
void resizeEvent(QResizeEvent *event);
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *event);
  1. We will implement the keyPressEvent() function in renderwindow.cpp:
void RenderWindow::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_W) { moveZ = -10; }
if (event->key() == Qt::Key_S) { moveZ = 10; }
if (event->key() == Qt::Key_A) { moveX = -10; }
if (event->key() == Qt::Key_D) { moveX = 10; }
}
  1. We will also implement the keyReleaseEvent() function:
void RenderWindow::keyReleaseEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_W) { moveZ = 0; }
if (event->key() == Qt::Key_S) { moveZ = 0; }
if (event->key() == Qt::Key_A) { moveX = 0; }
if (event->key() == Qt::Key_D) { moveX = 0; }
}
  1. After that, we will comment out the rotation code in paintEvent() and add the movement code, as highlighted in the following snippet. We do not want to get distracted by the rotation and just want to focus on the movement:
//rotation += deltaTime * 50;
movement.setX(movement.x() + moveX * deltaTime);
movement.setZ(movement.z() + moveZ * deltaTime);

QMatrix4x4 matrixMVP;
QMatrix4x4 model, view, projection;
model.translate(movement.x(), 1, movement.z());
  1. If you compile and run the program now, you should be able to move the cube around by pressing W, A, S, and D.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset