Pygame 命中框闪烁

Pygame hitboxes blinking

我正在尝试使用 pygame 制作游戏,我快完成了,但我想让绘制在墙壁对象中的框不闪烁,这些红色框在整个游戏过程中闪烁我不希望他们这样做,最后,我在 if 条件下调用 playercollide 函数,每当我创建新的对撞机时,我每次都必须在 if 条件下添加函数,我想要的是自动对撞机对象调用此函数,而无需我在 if 语句中为每个 collider 对象实例调用它。请指导我如何操作。

def redrawGameWindow():
    win.blit(bg, (-50,-200))
    man.draw(win)
    #man.drawhitbox(win)
    pygame.display.update()


#mainloop

man = player(200, 410, 64,64)
run = True
while run:
    collider1 = wall(500, 400, 200, 200, True)
    collider2 = wall(200,100,50, 50, False)
    collider3 = wall(700,100,50, 50, False)
    collider4 = wall(900,100,50,50, True)
    clock.tick(60)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    x, y = man.x, man.y

    if keys[pygame.K_a] and man.x > man.vel:
        x -= man.vel
        man.left = True
        man.right = False
    elif keys[pygame.K_d] and man.x < scrWidth - man.width - man.vel:
        x += man.vel
        man.right = True
        man.left = False
    elif keys[pygame.K_w] and man.y > man.vel:
        y -= man.vel
        man.left = False
        man.right = False
    elif keys[pygame.K_s] and man.y < scrHeight - man.height - man.vel:
        y+= man.vel
        man.left = False
        man.right = False
    else:
        man.right = False
        man.left = False
        man.walkCount = 0

    man.hitbox(15, 0, 31, 17)
    player_rect = pygame.Rect(x, y, 50, 55)
    if collider2.playerCollide(player_rect) == False and collider1.playerCollide(player_rect) == False and collider3.playerCollide(player_rect) == False and collider4.playerCollide(player_rect) == False:
        man.x, man.y = x, y
    redrawGameWindow()
pygame.quit()

问题是由多次调用 pygame.display.update() 引起的。从 class wall 中删除对 pygame.display.update() 的调用,并在 redrawGameWindow.
的末尾只执行 1 pygame.display.update() 但是,在画方框之前一定要先画背景,否则背景会盖住方框:

def redrawGameWindow():
    # win.blit(bg, (-50,-200)) <--- DELETE
    man.draw(win)
    #man.drawhitbox(win)
    pygame.display.update()
run = True
while run:
    win.blit(bg, (-50,-200)) # <--- ADD

    collider1 = wall(500, 400, 200, 200, True)
    collider2 = wall(200,100,50, 50, False)
    collider3 = wall(700,100,50, 50, False)
    collider4 = wall(900,100,50,50, True)

    # [...]

    redrawGameWindow()

通过创建碰撞器列表来简化代码:

colliders = [
   wall(500, 400, 200, 200, True),
   wall(200,100,50, 50, False),
   wall(700,100,50, 50, False),
   wall(900,100,50,50, True)] 
player_rect = pygame.Rect(x, y, 50, 55)
if not any(c.playerCollide(player_rect) for c in colliders):
    man.x, man.y = x, y