I honestly don't have an idea about how to notify the main widget that a collision has happened and delete the object from the scenes there.
If you derive your cannonball object from QGraphicsObject instead of QGraphicsItem, then it can have slots and signals. So, if you do your collision detection inside the cannonball code, then have it emit a signal "uhOhIAmAGoner( cannonball * unlucky )" that can be handled by a slot in the main window, view, or scene. Since the signal passes itself (this), you don't have to resort to tricks to find out which cannonball hit the mob.
class cannonball : public QGraphicsObject
{
Q_OBJECT;
// ...
signals:
void uhOhIAmAGoner( cannonball * unlucky );
protected slots:
void hitEnemy();
protected:
};
: QGraphicsObject( parent )
, timer( this )
{
timer.setInterval( 100 );
connect( &timer, SIGNAL( timeout() ), this, SLOT( hitEnemy() ) );
timer.start();
}
void cannonball::hitEnemy()
{
if ( collidedWithAMob() ) // You can figure this part out
{
timer.stop();
emit uhOhIAmAGoner( this );
}
else
updatePosition();
}
{
// ...
public slots:
void killThatCannonball( cannonball * cball );
protected:
void addACannonball();
private:
};
void MainWindow::addACannonball()
{
cannonball * cBall = new cannonball();
// establish initial trajectory, etc.
mobScene.addItem ( cBall );
connect( cBall, SIGNAL( uhOhIAmAGoner( cannonball * ) ), this, SLOT( killThatCannonball( cannonball * ) ) );
}
void MainWindow::killThatCannonball( cannonball * cBall )
{
mobScene.removeItem ( cBall );
delete cBall;
}
class cannonball : public QGraphicsObject
{
Q_OBJECT;
// ...
signals:
void uhOhIAmAGoner( cannonball * unlucky );
protected slots:
void hitEnemy();
protected:
QTimer timer;
};
cannonball::cannonball( QGraphicsItem * parent ) :
: QGraphicsObject( parent )
, timer( this )
{
timer.setInterval( 100 );
connect( &timer, SIGNAL( timeout() ), this, SLOT( hitEnemy() ) );
timer.start();
}
void cannonball::hitEnemy()
{
if ( collidedWithAMob() ) // You can figure this part out
{
timer.stop();
emit uhOhIAmAGoner( this );
}
else
updatePosition();
}
class MainWindow: public QMainWindow
{
// ...
public slots:
void killThatCannonball( cannonball * cball );
protected:
void addACannonball();
private:
QGraphicsScene mobScene;
};
void MainWindow::addACannonball()
{
cannonball * cBall = new cannonball();
// establish initial trajectory, etc.
mobScene.addItem ( cBall );
connect( cBall, SIGNAL( uhOhIAmAGoner( cannonball * ) ), this, SLOT( killThatCannonball( cannonball * ) ) );
}
void MainWindow::killThatCannonball( cannonball * cBall )
{
mobScene.removeItem ( cBall );
delete cBall;
}
To copy to clipboard, switch view to plain text mode
Of course, none of this code has been compiled and certainly not tested. That's why your professor gave it to you as a homework project...
Bookmarks