|
| 1 | +#include "Bullet.h" |
| 2 | +#include <QTimer> |
| 3 | +#include <QGraphicsScene> |
| 4 | +#include <QList> |
| 5 | +#include "Enemy.h" |
| 6 | +#include "Game.h" |
| 7 | + |
| 8 | +extern Game * game; // there is an external global object called game |
| 9 | + |
| 10 | +Bullet::Bullet(QGraphicsItem *parent): QObject(), QGraphicsPixmapItem(parent){ |
| 11 | + // draw graphics |
| 12 | + setPixmap(QPixmap(":/images/bullet.png")); |
| 13 | + |
| 14 | + |
| 15 | + // make/connect a timer to move() the bullet every so often |
| 16 | + QTimer * timer = new QTimer(this); |
| 17 | + connect(timer,SIGNAL(timeout()),this,SLOT(move())); |
| 18 | + |
| 19 | + // start the timer |
| 20 | + timer->start(50); |
| 21 | +} |
| 22 | + |
| 23 | +void Bullet::move(){ |
| 24 | + // get a list of all the items currently colliding with this bullet |
| 25 | + QList<QGraphicsItem *> colliding_items = collidingItems(); |
| 26 | + |
| 27 | + // if one of the colliding items is an Enemy, destroy both the bullet and the enemy |
| 28 | + for (int i = 0, n = colliding_items.size(); i < n; ++i){ |
| 29 | + if (typeid(*(colliding_items[i])) == typeid(Enemy)){ |
| 30 | + // increase the score |
| 31 | + game->score->increase(); |
| 32 | + |
| 33 | + // remove them from the scene (still on the heap) |
| 34 | + scene()->removeItem(colliding_items[i]); |
| 35 | + scene()->removeItem(this); |
| 36 | + |
| 37 | + // delete them from the heap to save memory |
| 38 | + delete colliding_items[i]; |
| 39 | + delete this; |
| 40 | + |
| 41 | + // return (all code below refers to a non existint bullet) |
| 42 | + return; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + // if there was no collision with an Enemy, move the bullet forward |
| 47 | + setPos(x(),y()-10); |
| 48 | + // if the bullet is off the screen, destroy it |
| 49 | + if (pos().y() < 0){ |
| 50 | + scene()->removeItem(this); |
| 51 | + delete this; |
| 52 | + } |
| 53 | +} |
0 commit comments