- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 339字
- 2021-08-27 18:31:10
The playing field
Since we will have to do some work on the scene, we subclass QGraphicsScene and name the new class MyScene. There, we implement one part of the game logic. This is convenient since QGraphicsScene inherits QObject and thus we can use Qt's signal and slot mechanism.
The scene creates the environment in which our elephant will be walking and jumping. Overall, we have a view fixed in size holding a scene, which is exactly as big as the view. We do not take size changes of the view into account, since they will complicate the example too much.
All animations inside the playing field are done by moving the items, not the scene. So we have to distinguish between the view's, or rather the scene's, width and the width of the elephant's virtual "world" in which he can move. In order to handle the movement properly, we need to create a few private fields in the MyScene class.
The width of this virtual world is defined by the int m_fieldWidth field and has no (direct) correlation with the scene. Within the range of m_fieldWidth, which is 500 pixels in the example, Benjamin or the graphics item can be moved from the minimum x coordinate, defined by qreal m_minX, to the maximum x coordinate, defined by qreal m_maxX. We keep track of his actual x position with the qreal m_currentX variable. Next, the minimum y coordinate the item is allowed to have is defined by qreal m_groundLevel. We have to also take into account the item's size.
Lastly, what is left is the view, which has a fixed size defined by the scene's bounding rectangle size, which is not as wide as m_fieldWidth. So the scene (and the view) follows the elephant while he walks through his virtual world of the m_fieldWidth length. Take a look at the following diagram to see the variables in their graphical representation: