我是 python 新手,我正在尝试使用 pygame 制作一个简单的平台游戏。我的问题是,当我使用
while
循环使方块下落直到它到达屏幕底部时,它会立即移动到那里,而我看不到它发生。然而,当我使用 if
语句将块从一侧移动到另一侧时,我可以看到这种情况发生。如何才能减慢下落的方块的速度,使其可见?
我大部分时间都在关注教程,但想添加我自己的东西。
clock = pygame.time.Clock()
fps = 60
run = True
while run:
clock.tick(fps)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
我也尝试将整个
while ... y = y + 5
代码放入 if
中;这减慢了它的速度,但只有当我按住 s
键时它才会移动。
如果你希望它完全“动画”下来,你应该添加在 while 循环中保持 pygame 屏幕/播放器更新的代码,否则你只是更改
y
而不更改屏幕。所以你的代码看起来有点像这样:
clock = pygame.time.Clock()
fps = 60
run = True
while run:
clock.tick(fps)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height)) # Make sure to update the player
pygame.display.update() # Make sure to update the display
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
更改 FPS:
但是,如果您确实想更改游戏循环的速度/本质上是每秒帧数,您可以简单地更改
fps
变量/clock.tick()
参数。例如:
clock = pygame.time.Clock()
fps = 30 # This value is the amount of frames per second
run = True
while run:
clock.tick(fps) # The argument (currently fps) passed into this method will change the frames per second
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x = x - 5
if keys[pygame.K_d] and x < (500 - width):
x = x + 5
if keys[pygame.K_s]: #this is the portion that is too fast.
while y < (500 - height):
y = y + 5
player = pygame.draw.rect(screen, (player_color), (x,y,width,height))
pygame.display.update()
您可以在
此处阅读有关
clock.tick()
方法的更多信息