I’m developing a shoot’em up with qt creator and my problem is the link with the keyPressEvent function of my scene:
void Scene::keyPressEvent(QKeyEvent *event){
liste_event << event->key();
if (liste_event.contains(Qt::Key_Left)) {
vaisseau->MoveX(-1);
}
if (liste_event.contains(Qt::Key_Right)) {
vaisseau->MoveX(1);
}
}
It compiles, but my sprite (vasisseau) moves very slowly. How can I improve the code so it moves faster?
Well, the problem is that you are leaving the animation of the game to the
keyPressEvent, which is not triggered as often as you would like.To solve this problem I suggest you use the traditional approach, which involves having an function to
draw()the scene (and it’s objects). The idea is that this function is called every X miliseconds, and the drawing will work independently of a key being pressed or not.So in this case, inside
keyPressEventyou would just store the key that was pressed, and inScene::draw()you will implement the logic that will callMoveX()with the appropriate parameter, based on the stored key.