【发布时间】:2017-10-01 03:39:45
【问题描述】:
这是我的第一个问题,也是我注册该网站的原因。我正在使用 Qt 5.9 开发游戏,并使用 QTimer 在屏幕上生成敌人。每次调用计时器的超时函数时,都会产生一个敌人。
我尝试做的是,如果玩家杀死 10 个敌人,计时器间隔会减少,因此敌人会更频繁地产生,使游戏更具挑战性。第一次设置了定时器间隔,游戏完美运行,但第二次调用setInterval()方法,当玩家杀死10个敌人时,游戏突然崩溃。我尝试调试它以找出可能导致它的原因,当我尝试设置 spawnInterval 时它似乎崩溃了。
我对编码还很陌生,所以任何建议都值得赞赏!以下是我的代码中的相关源文件和代码:
main.cpp
#include <QApplication>
#include <game.h>
Game * game;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
game = new Game();
game->show();
return a.exec();
}
游戏.h:
#include <QGraphicsScene>
#include <QWidget>
#include <QGraphicsView>
#include "Player.h"
#include "score.h"
#include "Health.h"
class Game: public QGraphicsView{
public:
Game(QWidget * parent=0);
QGraphicsScene * scene;
Player * player;
Score * score;
Health * health;
void setSpawnInterval(int spawnValue);
int getSpawnInterval();
void setTimerInterval();
private:
int spawnInterval = 1000;
};
#endif // GAME_H
游戏.cpp:
QTimer * timer1 = new QTimer();
QObject::connect(timer1,SIGNAL(timeout()),player,SLOT(spawn()));
timer1->start(getSpawnInterval());
}
void Game::setSpawnInterval(int spawnValue){
//this is the part where it crashes
spawnInterval = spawnValue;
}
int Game::getSpawnInterval(){
return spawnInterval;
}
分数.h
#ifndef SCORE_H
#define SCORE_H
#include <QGraphicsTextItem>
class Score: public QGraphicsTextItem{
public:
Score(QGraphicsItem * parent=0);
void increase();
int getScore();
private:
int score;
};
#endif // SCORE_H
分数.cpp
#include "score.h"
#include <QFont>
#include "game.h"
#include <QTimer>
void Score::increase()
{
score++;
if(score > 3){
Game * game;
game->setSpawnInterval(200);}
//Draw the text to the display
setPlainText(QString("Score: ") + QString::number(score));
}
int Score::getScore()
{
return score;
}
播放器.h
#ifndef PLAYER_H
#define PLAYER_H
#include <QGraphicsRectItem>
#include <QEvent>
#include <QObject>
class Player: public QObject, public QGraphicsRectItem{
Q_OBJECT
public:
Player(QGraphicsItem * parent=0);
void keyPressEvent(QKeyEvent * event);
int jumpPhaseNumber = 0;
bool jumpRun = false;
public slots:
void spawn();
void jumpPhase();
};
#endif
播放器.cpp
void Player::spawn()
{
Enemy * enemy = new Enemy();
scene()->addItem(enemy);
}
【问题讨论】:
-
游戏未初始化。
-
您的意思是:“Game *game = new Game()”而不是“Game *game”?我试过了,但它会创建一个新窗口,并且游戏会在该窗口中重新开始。
-
@Bencsizy 您是否可以在不启动计时器的情况下更改超时。像这样:
//timer1->start(getSpawnInterval());,timer1->setInterval(getSpawnInterval());我想确保更改时间间隔不是问题。 -
不!我的意思是你不能取消引用一个未初始化的变量。
-
试过了:如果我把那条线改成你提到的那条线,敌人就不会开始生成了。在那之后我添加了另一行:“timer1->start();”然后它们开始生成,但随后它像以前一样在 score = 3 处崩溃。