使玩家在Pygame中跳跃 [英] Making Player Jump in Pygame
问题描述
我正在使用pygame练习制作一个非常简单的游戏。我试图让我的玩家在按下空格键时跳转。这是我正在尝试的循环代码:
I'm making a very simple game using pygame to practice. Im trying to make my "player" jump when spacebar is pressed. Here is the loop code I'm trying:
x,y=10,300
movex,movey=0,0
if event.type==KEYDOWN:
if event.key==K_LEFT:
movex = -0.2
elif event.key==K_RIGHT:
movex=+0.2
elif event.key==K_DOWN:
movey=+0.2
elif event.key==K_SPACE:
movey=-0.4
movey=+0.4
if event.type==KEYUP:
if event.key==K_LEFT:
movex = 0
elif event.key==K_RIGHT:
movex=0
elif event.key==K_DOWN:
movey=0
elif event.key==K_SPACE:
movey=0
x+=movex
y+=movey
screen.blit(player,(x,y))
除了跳转部分(当我按空格键时)之外,控件均起作用。就像将播放器向下滑动一样。谁能告诉我为什么它不起作用以及如何解决?
The controls work except for the jump part (when I press the spacebar). It just like slides the player down. Can anyone tell me why it doesn't work and how to fix it?
推荐答案
它不起作用,因为发生KEYDOWN事件您正在执行以下操作:
It doesn't work because on KEYDOWN event you are doing:
movey=-0.4
movey=+0.4
最终等于 movey = 0
。要修复它,您应该只执行 movey = + 0.4
,然后在KEYUP上将其还原为0。
which in the end is equivalent to movey=0
. To fix it you should do only movey=+0.4
and then on KEYUP it will revert to 0.
这篇关于使玩家在Pygame中跳跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!