PDA

View Full Version : SpaceShip game



ado130
20th October 2017, 16:28
Hello,
I got a project to make SpaceShip game.
MainWindow.cc:

// Create scene for the game
scene_ = std::make_shared<QGraphicsScene>();

// Add player to the galaxy
//std::shared_ptr<PlayerShip> player = std::make_shared<PlayerShip>(galaxy_);
PlayerShip *player = new PlayerShip(scene_, galaxy_);
scene_->addItem(player);

// Add scene to the view
ui->graphicsView->setScene(scene_.get());
Playership.cc:

PlayerShip::PlayerShip(std::shared_ptr<QGraphicsScene> scene, std::shared_ptr<Student::Galaxy> galaxy)
{
galaxy_ = galaxy;
scene_ = scene;
}

void PlayerShip::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Left)
{
qDebug() << "Left";
setPos(x()-10, y());
}
else if(event->key() == Qt::Key_Right)
{
qDebug() << "Right";
setPos(x()+10, y());
}
else if(event->key() == Qt::Key_Up)
{
qDebug() << "Up";
setPos(x(), y()-10);
}
else if(event->key() == Qt::Key_Down)
{
qDebug() << "Down";
setPos(x(), y()+10);
}
else if(event->key() == Qt::Key_Space)
{
qDebug() << "Space";
// shoot
}

}
I can't figure out how to keep scene - the player in the middle of the scene, I mean, when the player is moving I want to also move the scene, so the game space will be endless. I added scene_ to the PlayerShip class, so e.g. I can set new x/y coordinates after player move, but Im not sure if is it correct way.
Second problem, I don't know, why does not work this code - does not work mean, the player ship will not show:

std::shared_ptr<PlayerShip> player = std::make_shared<PlayerShip>(scene_, galaxy_);
scene_->addItem(player.get());

Thank you for your advice.


Edit:
Well, here is my keyPressEvent function, but Im not sure about the implementation.

void PlayerShip::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Left)
{
setTransformOriginPoint(QPoint(18,7));
setRotation(rotation()-5);
}
else if(event->key() == Qt::Key_Right)
{
setTransformOriginPoint(QPoint(18,7));
setRotation(rotation()+5);
}
else if(event->key() == Qt::Key_Up)
{ // ToDo: movement is not correct
qreal diffX = 0, diffY = 0;
diffX = rect().width()-rect().x();
diffY = rect().height()-rect().y();
diffX *= cos( rotation() * PI / 180.0 );
diffY *= sin( rotation() * PI / 180.0 );
setPos(x() + diffX, y() + diffY);
// ToDo: check calculations
scene_->setSceneRect(scene_->sceneRect().x()+diffX, scene_->sceneRect().y()+diffY, scene_->sceneRect().width(), scene_->sceneRect().height());
}
else if(event->key() == Qt::Key_Down)
{ // ToDo: movement is not correct
qreal diffX = 0, diffY = 0;
diffX = rect().width()-rect().x();
diffY = rect().height()-rect().y();
diffX *= cos( rotation() * PI / 180.0 );
diffY *= sin( rotation() * PI / 180.0 );
setPos(x() - diffX, y() - diffY);
// ToDo: check calculations
scene_->setSceneRect(scene_->sceneRect().x()-diffX, scene_->sceneRect().y()-diffY, scene_->sceneRect().width(), scene_->sceneRect().height());
}
else if(event->key() == Qt::Key_Space)
{
qDebug() << "Space";
// shoot
}
}