我在摆弄pygame,试图创建一个简单的跳跃函数(还没有物理)。
出于某种原因,我的“跳转”在显示中不可见,即使我使用的值是打印出来的,并且看起来工作正常。我会做错什么?
isJump = False
jumpCount = 10
fallCount = 10
if keys[pygame.K_SPACE]:
isJump = True
if isJump:
while jumpCount > 0:
y -= (jumpCount**1.5) / 3
jumpCount -= 1
print(jumpCount)
while fallCount > 0:
y += (fallCount**1.5) / 3
fallCount -= 1
print(fallCount)
else:
isJump = False
jumpCount = 10
fallCount = 10
print(jumpCount, fallCount)
win.fill((53, 81, 92))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
我缩短了代码量,但我认为这是与问题相关的所有内容。
最佳答案
必须将while
循环转换为if
条件。你不想在一帧内完成整个跳跃。
你必须每帧跳一步。使用主应用程序循环执行跳转。
请参见示例:
import pygame
pygame.init()
win = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
isJump = False
jumpCount, fallCount = 10, 10
x, y, width, height = 200, 300, 20, 20
run = True
while run:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
isJump = True
if isJump:
if jumpCount > 0:
y -= (jumpCount**1.5) / 3
jumpCount -= 1
print(jumpCount)
elif fallCount > 0:
y += (fallCount**1.5) / 3
fallCount -= 1
print(fallCount)
else:
isJump = False
jumpCount, fallCount = 10, 10
print(jumpCount, fallCount)
win.fill((53, 81, 92))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.flip()
关于python - python,pygame-跳得太快?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58474204/