How does this algorithm make the character jump in pygame?
I have been watching Pygame tutorials to learn the module, and it came to the portion where the instructor shows you how to make your character jump. However, I am finding it impossible to understand the code they put down, and they did not explain it very well.
Can anyone break down for me the code below so I understand exactly what is happening? And is there a simpler way of coding a jump for a character? Please keep in mind I already have the code set up to where pressing the spacebar makes this code activate.
Isjump = False
Jumpcount = 10
#code for spacebar activation here, turns Isjump to True#
if Jumpcount >= -10:
Neg = 1
if Jumpcount < 0:
Neg = -1
y -= (Jumpcount ** 2) * 0.5 * Neg
Jumpcount -= 1
else:
Isjump = False
Jumpcount = 10
Solution 1:
At the started Jumpcount
is set 10.
Jumpcount = 10
The jump runs until Jumpcount
is less or equal -10. Therefore, a jump takes exactly 21 cycles:
if Jumpcount >= -10:
Neg
is "signe" of Jumpcount
. It is 1 if Jumpcount
is greater or equal to zero and -1 otherwise:
Neg = 1
if Jumpcount < 0:
Neg = -1
In each frame, the player's y
coordinate is changed by the quadratic function (Jumpcount ** 2) * 0.5
.
y -= (Jumpcount ** 2) * 0.5 * Neg
Since this term is multiplied by Neg
, it is positive if Jumpcount
is greater than 0, and 0 if Jumpcount
is 0, otherwise it is less than 0.
When the amount of Jumpcount
is large, the change in the y
coordinate is greater than when the amount is small. See the values for (Jumpcount ** 2) * 0.5 * Neg
in the 21 cycles:
50.0, 40.5, 32.0, 24.5, 18.0, 12.5, 8.0, 4.5, 2.0, 0.5, 0.0,
-0.5, -2.0, -4.5, -8.0, -12.5, -18.0, -24.5, -32.0, -40.5, -50.0
At the beginning the values are positive and the player jumps. In the end the values are negative and the player falls down.
The sum of this values is 0. Therefore the y
-coordinate has the same value at the end as at the beginning.
See also How to make a character jump in Pygame?.