- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 326字
- 2021-08-27 18:31:14
Finishing the game
The last part we have to discuss is the scene's initialization. Set the initial values for all fields and the constructor, create the initPlayField() function that will set up all the items, and call that function in the constructor. First, we initialize the sky, trees, ground, and player item:
void MyScene::initPlayField()
{
setSceneRect(0, 0, 500, 340);
m_sky = new BackgroundItem(QPixmap(":/sky"));
addItem(m_sky);
BackgroundItem *ground = new BackgroundItem(QPixmap(":/ground"));
addItem(ground);
ground->setPos(0, m_groundLevel);
m_trees = new BackgroundItem(QPixmap(":/trees"));
m_trees->setPos(0, m_groundLevel - m_trees->boundingRect().height());
addItem(m_trees);
m_grass = new BackgroundItem(QPixmap(":/grass"));
m_grass->setPos(0,m_groundLevel - m_grass->boundingRect().height());
addItem(m_grass);
m_player = new Player();
m_minX = m_player->boundingRect().width() * 0.5;
m_maxX = m_fieldWidth - m_player->boundingRect().width() * 0.5;
m_player->setPos(m_minX, m_groundLevel - m_player->boundingRect().height() / 2);
m_currentX = m_minX;
addItem(m_player);
//...
}
Next, we create coin objects:
m_coins = new QGraphicsRectItem(0, 0, m_fieldWidth, m_jumpHeight); m_coins->setPen(Qt::NoPen); m_coins->setPos(0, m_groundLevel - m_jumpHeight); const int xRange = (m_maxX - m_minX) * 0.94; for (int i = 0; i < 25; ++i) { Coin *c = new Coin(m_coins); c->setPos(m_minX + qrand() % xRange, qrand() % m_jumpHeight); } addItem(m_coins);
In total, we are adding 25 coins. First, we set up an invisible item with the size of the virtual world, called m_coins. This item should be the parent to all coins. Then, we calculate the width between m_minX and m_maxX. That is the space where Benjamin can move. To make it a little bit smaller, we only take 94 percent of that width. Then, in the for loop, we create a coin and randomly set its x and y position, ensuring that Benjamin can reach them by calculating the modulo of the available width and of the maximal jump height. After all 25 coins are added, we place the parent item holding all the coins on the scene. Since most coins are outside the actual view's rectangle, we also need to move the coins while Benjamin is moving. Therefore, m_coins must behave like any other background. For this, we simply add the following code to the movePlayer() function, where we also move the background by the same pattern:
applyParallax(ratio, m_coins);