Browse Source

Tut 10

master
Georg Spar 2 years ago
parent
commit
6a15fa0d63
  1. 1
      CMakeLists.txt
  2. 20
      bullet.cpp
  3. 14
      bullet.h
  4. 13
      game.cpp
  5. 2
      game.h
  6. BIN
      missile.png
  7. 2
      res.qrc

1
CMakeLists.txt

@ -19,6 +19,7 @@ set(PROJECT_SOURCES
tower.h tower.cpp tower.h tower.cpp
game.h game.cpp game.h game.cpp
res.qrc res.qrc
bullet.h bullet.cpp
) )
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)

20
bullet.cpp

@ -0,0 +1,20 @@
#include "bullet.h"
#include <QTimer>
#include <qmath.h>
Bullet::Bullet(QGraphicsItem *parent) {
// set graphics
setPixmap(QPixmap(":/images/missile.png"));
QTimer *move_timer = new QTimer(this);
connect(move_timer, SIGNAL(timeout()), this, SLOT(move()));
move_timer->start(50);
}
void Bullet::move() {
int STEP_SIZE = 30;
int theta = rotation(); // degrees
double dy = STEP_SIZE * qSin(qDegreesToRadians(theta));
double dx = STEP_SIZE * qCos(qDegreesToRadians(theta));
setPos(x()+dx, y()+dy);
}

14
bullet.h

@ -0,0 +1,14 @@
#ifndef BULLET_H
#define BULLET_H
#include <QGraphicsPixmapItem>
#include <QObject>
class Bullet: public QObject, public QGraphicsPixmapItem {
Q_OBJECT
public:
Bullet(QGraphicsItem *parent=0);
public slots:
void move();
};
#endif // BULLET_H

13
game.cpp

@ -1,10 +1,11 @@
#include "game.h" #include "game.h"
#include <QGraphicsScene> #include <QGraphicsScene>
#include "tower.h" #include "tower.h"
#include "bullet.h"
Game::Game() { Game::Game() {
scene = new QGraphicsScene(this); scene = new QGraphicsScene(this);
scene->setSceneRect(0,0,800,600);
setScene(scene); setScene(scene);
// create a tower // create a tower
@ -14,4 +15,14 @@ Game::Game() {
scene->addItem(t); scene->addItem(t);
setFixedSize(800,600); setFixedSize(800,600);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
void Game::mousePressEvent(QMouseEvent *event) {
// create a bullet
Bullet *bullet = new Bullet();
bullet->setPos(event->pos());
bullet->setRotation(40);
scene->addItem(bullet);
} }

2
game.h

@ -2,11 +2,13 @@
#define GAME_H #define GAME_H
#include <QGraphicsView> #include <QGraphicsView>
#include <QMouseEvent>
class Game : public QGraphicsView class Game : public QGraphicsView
{ {
public: public:
Game(); Game();
void mousePressEvent(QMouseEvent *event);
QGraphicsScene *scene; QGraphicsScene *scene;
}; };

BIN
missile.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

2
res.qrc

@ -1,5 +1,7 @@
<RCC> <RCC>
<qresource prefix="/images"> <qresource prefix="/images">
<file>tower.png</file> <file>tower.png</file>
<file>missile.png</file>
</qresource> </qresource>
<qresource prefix="/"/>
</RCC> </RCC>

Loading…
Cancel
Save