You probably won't want to do this because you'll be retrieving the "collidingItems" collection *twice* for every pass through the loop. Retrieve it *once* before the loop starts and assign it to some temporary variable, then use that variable to get the count, etc.
What do you want to happen when the cannonball hit detection returns true? The cannonball goes away? Then you simply need to remove the cannonball instance from the scene.
QGraphicsScene::removeItem()
for (int i = this->pos().x(); i < 640; ++i)
{
animation
->setPosAt
(i
/ 640.0,
QPointF(i, this
->pos
().
y() ));
if (hits_enemy())
timer->setCurrentTime(0);
}
for (int i = this->pos().x(); i < 640; ++i)
{
animation->setPosAt(i / 640.0, QPointF(i, this->pos().y() ));
if (hits_enemy())
timer->setCurrentTime(0);
}
To copy to clipboard, switch view to plain text mode
And why is this code in the cannonball constructor? The instance isn't even in the scene at this point, so how can it collide with anything?
You need to set up a timer in your main window (or in your QGraphicsView, if you have derived a custom one) that fires a couple of times per second so the animation looks smooth. In the slot that handles each time step timeout, you retrieve all the cannonball instances from the scene, and *then* do the hit detection on them.
// pseudocode:
for each cannonball
{
QList<QGraphicsItem *> colliders = scene.collidingItems( cannonball );
if ( colliders is not empty && colliders contains a mob )
add cannonball to list of items to be deleted
}
for each cannonball on the deletion list
{
scene.removeItem( cannonball )
delete cannonball;
}
// pseudocode:
for each cannonball
{
QList<QGraphicsItem *> colliders = scene.collidingItems( cannonball );
if ( colliders is not empty && colliders contains a mob )
add cannonball to list of items to be deleted
}
for each cannonball on the deletion list
{
scene.removeItem( cannonball )
delete cannonball;
}
To copy to clipboard, switch view to plain text mode
You might also consider putting a timer inside each cannonball; at each timeout, it updates the cannonball's position by moving it further along its trajectory. If you derive your cannonballs from QGraphicsObject, then you can handle the x/y/zChanged() signals from each cannonball and do the collision detection there instead of in a slot driven by a master clock. Use
QObject::sender() to determine which cannonball sent the signal, or use
QSignalMapper to associate the cannonball instance.
Bookmarks