Item collision detection
Whether the player item collides with a coin is checked by the scene's checkColliding()
function, which is called after the player item has moved horizontally or vertically.
Time for action - Making the coins explode
The implementation of checkColliding()
looks like this:
void MyScene::checkColliding() { for(QGraphicsItem* item: collidingItems(m_player)) { if (Coin *c = qgraphicsitem_cast<Coin*>(item)) { c->explode(); } } }
What just happened?
First, we call the scene's QGraphicsScene::collidingItems()
function, which takes the item for which colliding items should be detected as a first argument. With the second, optional argument, you can define how the collision should be detected. The type of that argument is Qt::ItemSelectionMode
, which was explained earlier. By default, an item will be considered colliding with m_player
if the shapes of the two items intersect.
Next, we loop through the list of found items and check whether...