【问题标题】:Resembling gravity in python using pygame使用pygame在python中类似重力
【发布时间】:2014-02-04 22:05:41
【问题描述】:

在这个程序中,我正在创建一个从 (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()

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多