-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbullet.cpp
More file actions
94 lines (89 loc) · 2.46 KB
/
bullet.cpp
File metadata and controls
94 lines (89 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "bullet.h"
#include <QTimer>
#include <QBrush>
#include "player.h"
#include "enemy.h"
#include <QGraphicsScene>
#include <QMediaPlayer>
/*
Function: Bullet Constructor
Params: int x, int y, Direction, scene, bound
Desc: Instantiates bullet class given certain perams
Returns: none
*/
Bullet::Bullet(int x, int y, Direction dir, QGraphicsScene * scene, Bounds bound)
{
this->scene = scene;
dir_ = dir;
QPixmap qp(":/images/bullet.png");
qp = qp.scaled(30, 30);
setPixmap(qp);
//Start the timer for bullet movement
QTimer * timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(Travel()));
timer->start(30);
setPos(x, y);
bound_ = bound;
}
/*
Function: travel
Params: none
Desc: Travels in a given direction every tick
Returns: none
*/
void Bullet::Travel() {
if (x() < bound_.x1 || x() > bound_.x2 || y() < bound_.y1 || y() > bound_.y2) {
scene->removeItem(this);
delete this;
return;
}
if (delay_timer > 0) {
delay_timer --;
return;
}
//Move in the correct direction given
switch (dir_) {
case(Direction::S):
setY(y() + 10);
break;
case(Direction::N):
setY(y() - 10);
break;
case(Direction::W):
setX(x() - 10);
break;
case(Direction::E):
setX(x() + 10);
break;
case(Direction::NE):
setY(y() - 10);
setX(x() + 10);
break;
case(Direction::NW):
setY(y() - 10);
setX(x() - 10);
break;
case(Direction::SE):
setY(y() + 10);
setX(x() + 10);
break;
case(Direction::SW):
setY(y() + 10);
setX(x() - 10);
}
//If the bullet collides with a player, the player should lose health!
QList<QGraphicsItem *> colliding_items = collidingItems();
for (size_t i = 0,n = colliding_items.size(); i < n; ++i){
if (dynamic_cast<Player *>(colliding_items[i]) && !dynamic_cast<Enemy *>(colliding_items[i])){
this->scene->removeItem(this);
Player * p = static_cast<Player *>(colliding_items[i]);
p->changeHealth(-1);
this->scene->update();
QMediaPlayer * sound = new QMediaPlayer();
sound->setMedia(QUrl("qrc:/sounds/hit.wav"));
sound->play();
delete this;
return;
}
}
}