これは私がサイトにサインアップした理由です。私はQt 5.9を使ってゲームを開発しています。私はQTimerを使ってスクリーンに敵を召喚します。タイマーのタイムアウト機能が呼び出されるたびに、敵が発生します。 私がしようとしているのは、プレイヤーが10人の敵を殺すとタイマー間隔が減少するため、敵がより頻繁に出現し、ゲームを少し難しくする場合です。初めてタイマー間隔が設定されると、ゲームは完全に実行されますが、setInterval()
メソッドが呼び出された2回目に、プレイヤーが10人の敵を殺すと、ゲームが突然クラッシュします。私はそれを引き起こす可能性があることを理解するためにそれをデバッグしようとしました、そして、私はspawnIntervalを設定しようとするとクラッシュするようです。 私はかなり新しくコーディングするので、アドバイスをいただければ幸いです!ここに私のコードから、関連するソースファイルとコードは次のとおりです。Qtimer間隔を設定するとQtアプリケーションがクラッシュする
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