Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - How to make a 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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...