【问题标题】:Pygame Erasing Images on BackgroundsPygame 擦除背景上的图像
【发布时间】:2012-02-15 01:31:47
【问题描述】:

您将图像粘贴到表面上以用作背景。然后按下按钮 X 在同一表面上对图像进行 blit,如何擦除图像?到目前为止我有这个,但最后我的背景中间有一个白色矩形。

screen = pygame.display.set_mode(1280, 512)

screen.blit(background, (0,0))

while True:   
    pygame.display.flip() #flip is same as update
    for event in pygame.event.get():
        if (event.type == pygame.KEYDOWN):        
            if event.key == pygame.K_SPACE:
                screen.blit(player, (x, y))
            if event.key == pygame.K_BACKSPACE:
                pygame.draw.rect(screen, [255,255,255], (x, y, 62,62))

【问题讨论】:

    标签: python wxpython pygame


    【解决方案1】:

    您可以在这里做两件事。您可以走简单的路线,然后再次绘制背景...

    if event.key == pygame.K_BACKSPACE:
       screen.blit(background, (0,0))
    

    或者,如果你想让它更高效一点,你可以让 blit 方法只绘制玩家图像覆盖的背景部分。你可以这样做......

    screen.blit(background, (x, y), pygame.Rect(x, y, 62, 62))
    

    第三个参数中的 Rect 将导致 blit 仅绘制位于图像上位置 x,y 的“背景”的 62x62 像素部分。

    当然,这假设玩家图像始终在背景中。如果播放器图像仅部分重叠背景,我不完全确定会发生什么。它可能会抛出异常,或者它只会环绕到图像的另一侧。

    如果这是一个相当小的项目,第一个选项确实应该没问题,但如果您出于某种原因担心性能,请尝试第二个选项。

    【讨论】:

    • 如果我选择第一个选项,它会覆盖我的其他图层(我在屏幕上粘贴的其他图像)。然而!第二个选项就像一个魅力,谢谢!
    【解决方案2】:

    通常,blit 工作流程只是将原始背景blit 到屏幕上。

    在您的代码中,您将使用screen.blit(background, (0,0))

    当您开始组合大量表面时,您可能需要一个变量或变量列表来跟踪屏幕状态。

    例如

    初始化背景

    objectsonscreen = []
    objectsonscreen.append(background)
    screen.blit(background, (0,0))
    

    添加精灵

    objectsonscreen.append(player)
    screen.blit(player, (x, y))
    

    清除精灵

    objectsonscreen = [background]
    screen.blit(background, (0,0))
    

    有关 Pygame 中精灵的更多信息,请参阅 here。请注意,如果您的背景不是图像背景而只是纯色,您也可以改用screen.fill([0, 0, 0])

    【讨论】:

    • 您提到了“添加精灵”。我经常看到这个词。但是这是什么意思?它只是一个前景,并且比背景小的东西吗?
    • 见维基百科文章here
    【解决方案3】:

    我个人使用

    pygame.draw.rect(screen, (RgbColorHere), (x, y, width, height))
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多