equati0n equati0n -4 years ago 129
C++ Question

How to keep firing bullets in QT game

my question is how to keep firing bullets in my game. I can fire 1 bullet and then I get the message QGraphicsScene::addItem: item has already been added to this scene. I have read a few posts on similar topic, however the explanation did not solve my problem. Here is my code snippets. I understand that the item is already added, but how to get around this and keep shooting bullets? Any help or example code would be greatly appreciated.

void LevelOne::keyPressEvent(QKeyEvent *event) {
if (event->isAutoRepeat())
return;

switch (event->key()) {

case Qt::Key_F:
addItem(bullet); // Add the bullet
break;
case Qt::Key_Space:

break;
default:
break;
}
}


void LevelOne::initPlayField() {

bullet = new Bullet() ;
bullet->setPos(m_player->pos().x(), m_player->pos().y()
}

Answer Source

What I understand is that you want to throw bullets when you press the F key, every bullet is new, so you must create that object every time.

void LevelOne::keyPressEvent(QKeyEvent *event) {
    if (event->isAutoRepeat())
            return;

    switch (event->key()) {

    case Qt::Key_F:
       Bullet *obj = new Bullet();
       obj->setPos(m_player->pos().x(),  m_player->pos().y()
       addItem(obj);          // Add the bullet
       break;
    case Qt::Key_Space:     

        break;
    default:
        break;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download