1 回答

TA贡献1942条经验 获得超3个赞
不要在while循环中定义位置和速度变量,否则它们将在每帧(循环的迭代)中重置。相反,在循环外定义它们并通过增加速度来改变循环内的位置。
我还建议使用一个pygame.Rect对象,而不是独立的thing_startx,thing_starty,thing_width和thing_height变量:
# Pass the top left coordinates, the width and the height.
thing_rect = pygame.Rect(random.randrange(display_width), -60, 30, 30)
然后通过添加每帧的速度来更新其 y 坐标:
thing_rect.y += thing_speed
这是一个最小的完整示例:
import pygame
import random
pygame.init()
display_width = 1000
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()
stmenpic = pygame.Surface((30, 50))
stmenpic.fill((0, 200, 50))
def start_menu():
thing_rect = pygame.Rect(random.randrange(display_width), -60, 30, 30)
thing_speed = 7
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
# Move the rect downwards.
thing_rect.y += thing_speed
# Reset the position of the rect when it leaves the screen.
if thing_rect.y > display_height:
thing_rect.y = 0 - thing_rect.height
thing_rect.x = random.randrange(display_width)
gameDisplay.fill((30, 30, 30))
gameDisplay.blit(stmenpic, thing_rect) # Blit the image at the rect.
pygame.display.update()
clock.tick(60)
start_menu()
pygame.quit()
如果你想要多个落下的物体,只需将一些矩形放入一个列表中并使用for循环来更新和绘制它们。
添加回答
举报