這是我第一個問題,我登錄該網站的原因。我正在開發一款使用Qt 5.9的遊戲,並使用QTimer在屏幕上產生敵人。每當定時器的超時功能被調用時,就會產生一個敵人。 我試圖做的是如果一個玩家殺了我們說10個敵人,定時器間隔減少,所以敵人會更頻繁地產卵,使得遊戲更具挑戰性。定時器間隔第一次設置時,遊戲運行完美,但第二次調用方法時,當玩家殺死10個敵人時,遊戲突然崩潰。我試着調試它來找出可能導致它的原因,當我嘗試設置spawnInterval時,它似乎崩潰了。 我是相當新的編碼,所以任何建議表示讚賞!下面是相關的源文件和代碼從我的代碼:Qt設置QTimer間隔時應用程序崩潰
的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();
}
game.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
game.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
score.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;
}
player.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
player.cpp
void Player::spawn()
{
Enemy * enemy = new Enemy();
scene()->addItem(enemy);
}
遊戲未初始化。 –
你的意思是:「遊戲*遊戲=新遊戲()」而不是「遊戲*遊戲」?我試了一下,但它創建了一個新窗口,遊戲再次在該窗口中開始。 – Bencsizy
@Bencsizy是否有可能在沒有啓動計時器的情況下更改超時時間。像這樣:''timer1-> start(getSpawnInterval());','timer1-> setInterval(getSpawnInterval());'我想確保更改時間間隔不是問題。 – aghilpro