在这个程序中,我正在创建一个从(0,0)开始的正方形,并且每次围绕循环(类似于重力)下降速度增加一个,当它跳到屏幕底部时跳到顶部每次绕循环减慢一个然后重复。下面的代码一直工作,直到方块第一次回到顶部,它被卡住了。有关如何解决此问题的任何建议?谢谢。
rect_x = 0
rect_y = 0
speed = 0
rect_change_x = 10
rect_change_y = 0
# Set the width and height of the screen [width,height]
size = [800,600]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Lovely Game")
#Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while done == False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
if rect_x > 750 or rect_x < 0:
rect_change_x *= -1
if rect_y > 550:
rect_change_y = -rect_change_y
if rect_y < 0:
rect_change_y = 0
rect_x += rect_change_x
rect_y += rect_change_y
screen.fill(black)
rect_change_y = rect_change_y + 1
pygame.draw.rect(screen,white,[rect_x,rect_y,50,50])
pygame.display.set_caption(str(rect_change_y))
pygame.display.flip()
# Limit to 30 frames per second
clock.tick(30)
pygame.quit()
答案 0 :(得分:0)
if rect_y < 0:
rect_change_y = 0
这是导致问题的一行。当矩形位于屏幕顶部边缘上方时,您将其y速度设置为0.然后,由于其速度为零,因此它不会低于屏幕边缘的那一帧。虽然每帧增加一个速度,但它会在下一帧再次重置为零,依此类推。
我建议更改块,以便取消所有向上速度,但不向下取消。
if rect_y < 0:
rect_change_y = max(rect_change_y, 0)
或者,对于弹性碰撞,只需翻转标志。
if rect_y < 0:
rect_change_y *= -1