有没有一种方法可以减少pygame的更新?

时间:2019-06-04 22:07:30

标签: python pygame

我对pygame的运行速度有疑问。当我在广场上施力时,它会立即消失。

我尝试使用较小的数字,但似乎无法使其稳定运行。

screen = pg.display.set_mode((640, 480))

x, y = 200, 200

xvel, yvel = 0, 0

xaccel, yaccel = 0, 0

def update_rect():
    global x, y, xvel, yvel, xaccel, yaccel
    x += xvel
    y += yvel

    xvel += xaccel
    yvel += yaccel

    xaccel, yaccel = 0, 0

def apply_force(fx, fy):
    global xaccel, yaccel
    xaccel += fx
    yaccel += fy

while True:
    screen.fill((0, 0, 0))
    pg.draw.rect(screen, (255, 255, 255), (x, y, 40, 40), 0)

    pg.display.update()
    update_rect()
    apply_force(0, 0.1)



    handle_keys()

我的预期结果是该矩形将从屏幕上缓慢掉下,但立即消失。

1 个答案:

答案 0 :(得分:1)

您应该使用时钟来减慢while循环。为此,您可以轻松创建一个pygame.time.Clock实例,并在您的while循环中使用tick(FPS)方法。勾号方法采用一个值作为您想要的FPS。

import pygame as pg

screen = pg.display.set_mode((640, 480))

x, y = 200, 200

xvel, yvel = 0, 0

xaccel, yaccel = 0, 0

clock = pg.time.Clock() # created the clock here.

def update_rect():
    global x, y, xvel, yvel, xaccel, yaccel
    x += xvel
    y += yvel

    xvel += xaccel
    yvel += yaccel

    xaccel, yaccel = 0, 0

def apply_force(fx, fy):
    global xaccel, yaccel
    xaccel += fx
    yaccel += fy

while True:
    screen.fill((0, 0, 0))
    pg.draw.rect(screen, (255, 255, 255), (x, y, 40, 40), 0)

    pg.display.update()
    update_rect()
    apply_force(0, 0.1)

    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            quit()

    clock.tick(30) # you can change the value as you wish.