python - "pygame.display.update()"没有清除blit图像

标签 python pygame

我有一个主循环,可以在某个点更新图像:

循环:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    self.spaceship.buttons()
    self.spaceship.update(self.screen)
    pygame.display.update()

其中 self.spaceship.buttons() 是:

def buttons(self):
    key = pygame.key.get_pressed()
    dist = 1
    if key[pygame.K_LEFT]:
        self.x -= dist
    elif key[pygame.K_RIGHT]:
        self.x += dist

并且定义了self.spaceship.update(self.screen):

def update(self, surface):
    surface.blit(self.image, (self.x, self.y))

主循环更新按键并将图像“传输”到屏幕上后,它应该更新显示(pygame.display.update()),但屏幕没有不会被清除。这是移动之前和之后的显示效果:

This is what the image looks like before the blit at a different position

This is what the image looks like after the blit is at a different position (after moving)

为什么pygame.display.update()没有清除图像的前几帧?

最佳答案

这很简单,pygame 不会为你做这个。
pygame.display.update() 更新整个场景,向用户显示您“blipped”的新内容。它不会抹去过去。

它也可用于仅更新您知道已完成某些更新的某些区域(以加快速度)。

或者,您可以执行 flip() 来更新整个图形缓冲区,使其仅包含自上次翻转以来您已翻转的新内容(请注意,您将丢失本次翻转中未包含的所有内容)周期):

while True:
    ...
    pygame.display.flip()

或者,您只需在调用更新之前“绘制”一个黑框即可。
然而,这要费力得多。

while True:
    ...
    self.screen.fill((0,0,0))
    pygame.display.update()

我的建议是您可以使用 draw_rect并在宇宙飞船所在的先前区域上绘制一个黑色矩形,或者简单地使用 flip() 交换到 GPU 中的新缓冲区页面。在大多数实现中,flip() 的执行速度非常快。

我来自 Pyglet 背景,因此 flip()update()draw_rect() 的速度性能可能会有所不同在 Pygame 中,但基本原理应该是相同的,我的答案应该是有效的,如果不是,请指出这一点。

关于python - "pygame.display.update()"没有清除blit图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705361/

相关文章:

python - 使用 Opencv SIFT 时 matches1to2 出错

python - 如何在pandas中groupby之后获得两组之间的p值?

python - 抑制复合假设策略的 HealthCheck.too_slow

python - pygame : Why does calling a function inside the game loop inside Game loop make my game lag?

python - 你能让 Pygame 在视网膜屏幕上正常工作吗?

python - 样本数(行)标准化的方法

python - Pygame,OpenGL : Project 3D rgb values to 2D surface

python - 处理自上而下 View 游戏的旋转 Sprite 的最佳方法是什么

python - 无法再添加三个立方体

Python - Pygame 突然变慢