'Keeping old values of variable in constructor in qt and cpp
I am using Qt and Cpp (on windows 10). I have a situation in my application. The application is a Falling Ball game. Basically, the game is that balls keeps on falling at regular intervals of 3 secs. There is a rectangle that acts as a basket to catch the ball. I have defined the dimensions of the ball and basket in the Sprite class as shown below. My question is, as I have sprites being created at regular intervals, the dimensions of the BAR(rectangular basket x1 and y1) are defined in the Sprite constructor. Whenever I create a new sprite every 3 secs, the default values of x1 and y1 are set ignoring the current values obtained by the position of the basket. How can I keep the old values of x1 and y1, while creating new sprites at regular intervals?
Sprite.h
int x=0;//position of sprite in x-direction.
int y=0;//position of sprite in y-direction.
int dx=1;//difference in x-direction position.
int dy=1;//difference in y-direction position.
int x1=0;//position of the basket in x-direction
int y1=0 ;//position of the basket in y-direction.
Sprite.cpp
Sprite::Sprite(QWidget *p)
{
parent=p;
QRect rct = parent->rect();
x = rand() % rct.width();//randomly initialize the x-position for the sprite.
y=rct.height()*0.05;//start position for the sprite is about 5% after the top of the menu bar.
dx = rand() % 10;//the speed is randomly set in x-direction.
dy = 4;
x1=rct.width()/2;
y1 = rct.height() - 80;
start(10);
}
void Sprite::drawBall(QPainter &painter)
{
painter.drawEllipse(x, y, 15, 15);
}
void Sprite::drawBar(QPainter &painter)
{
painter.drawRect( x1, y1, 80, 30);
}
void Sprite::move(int nDirection)
{
QRect rct = parent->rect();
if(nDirection == 0)
{
if(x1 >= 0 ) x1 += -15;
}
else
{
if(x1+80 < rct.width()){x1 += 15;}
}
}
void Sprite::timerEvent(QTimerEvent *event)
{
QRect rct = parent->rect();
if ( x > rct.width() || x < 0)
dx *= -1;
if ( y > rct.height() || y < 0)
dy *= 1;
if (event->timerId() == timerId1)
{
qDebug() << "Timer ID:" << event->timerId();
}
x += dx;
y += dy;
if( (((y - 15) >= 520)&& y <550 ) && ( (x <= (x1 + 80)) && (x >= (x1 - 80)) ))
{
qDebug("x and y position when condition is met and also x1 and y1");
qDebug()<<x;
qDebug()<<y;
qDebug()<<x1;
qDebug()<<y1;
dy *= -1;
dx *= -1;
}
parent->update();
}
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug() <<"mainWindow constructor";
QTimer *timer;
timer=new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::onTimer);
timer->start(3000);
}
void MainWindow::onTimer()
{
sprite = new Sprite(this);
connect(this, &MainWindow::draw, sprite, &Sprite::drawBall);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
