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

标签 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()


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

最佳答案

您应该使用时钟来减慢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.

关于python - 有没有一种方法可以减少pygame的更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56451944/

相关文章:

python - Python 中的 "List index out of range"错误

python - 使用 xlwt 将超链接添加到带有文本的单元格

python - 在 Python 中检测 64 位操作系统(Windows)

python - 当我使用 pygame.sprite.spritecollide() 时,为什么只有子弹消失了?

python - 在 Kivy 中使用 sdl2 而不是 pygame

python - 如何在 Windows8 上安装 Pygame 以使用 Python 3.3.3?

python - 从列表中解压的类继承

python - 如何用列表中的单词替换重复多次的单个单词?

python - 如何使用python返回mysql查询结果

python - 有没有办法在 pygame 中 blit 多个图像或图像列表