Making Label Jump using PyQt5 in Python
Prerequisite: Introduction to PyQt5
PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.
NOw, we will see how we can make the label jump. Sometimes there is a need to make the label jump while designing 2-D games in PyQt5, Jumping label is a label which when pressed jump key(here space bar) goes up and its speed of going up decreases and when it attains the maximum height, it starts going down with the increase in speed. Speed decreases while going up and decreases while going down it due to the gravity effect.
Concept : We can make the label jump by changing its Y co-ordinate with the time, we can get the Y co-ordinate for each time with the help of basic formula from classical mechanics i.e given below :
Force = 1/2 * mass * velocity^2
By decrementing this force value from the initial Y co-ordinate will give us the new Y co-ordinate for each time and then decrementing the speed.
Implementation Steps :
1. Create a main window.
2. Create a jump flag, and a speed and mass variable.
3. Create a label.
4. Set label geometry and the style sheet.
5. Override the key press event.
6. Inside the key press event check when the space bar key is pressed.
7. If space bar key is pressed make the jump variable true.
8. Create a timer object and add action to the timer which get called after every 50 milliseconds.
9. Inside the timer action get the Y co-ordinate of the label and check if the jump flag is true.
10. If jump flag is true calculate the force and decrement the force value from the Y co-ordinate and set the new position to the label.
11. If the speed becomes zero make the mass negative, and if the label comes back to normal position make the jump flag false and reset the value of mass and speed.
Below is the implementation :