如何在pygame中进行双跳?
有人可以帮我调试我的代码,因为我不明白为什么我不能让我的角色使用多个空格键进行双跳。当我运行脚本时,我可以向上、向下、向左、向右移动,但是一旦我按一次空格键,对象就会飞出窗口。
问题来自这个 if 语句,所以我猜这个 if 语句继续运行并增加我的 jumpCount,我无法理解,因为在按一次空格后不应该keys[pygame.K_SPACE]评估为 true 然后再次返回 false 所以这个除非我按下另一个空格键,否则 if 语句不应运行?
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
这是我的脚本:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 5 #To calculate the height I have to rise by
number_to_compensate = 0 #So the more times I press space(higher I jump) the more I have to fall by
run = True
while run:
pygame.time.delay(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - vel - width:
x += vel
if not (isJump):
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
number_to_compensate += 1
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
if jumpCount >= -5 *number_to_compensate:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 5
isJump = False
number_to_compensate = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
回答
对于您想要的,您需要更改一些跳转算法。根据加速度和速度计算跳跃。
定义重力和跳跃加速度的常数:
PLAYER_ACC = 15
PLAYER_GRAV = 1
使用键盘事件进行跳转,而不是pygame.key.get_pressed(). 键盘事件(请参阅pygame.event模块)仅在键状态更改时发生一次。KEYDOWN每次按下一个键时该事件发生一次。KEYUP每次释放键时发生一次。将键盘事件用于单个操作。
设置space按下时的跳跃加速度:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
根据加速度和 y 坐标根据每一帧中的速度更改速度:
vel_y += acc_y
y += vel_y
通过地面限制 y 坐标:
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
最小的例子:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()
ground_y = 400
x, y = 200, ground_y
width, height = 40, 60
vel_x, vel_y = 5, 0
acc_y = 0
PLAYER_ACC = 15
PLAYER_GRAV = 1
run = True
while run:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel_x
x = max(0, min(500 - width, x))
vel_y += acc_y
y += vel_y
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
clock.tick(60)
pygame.quit()