What is a good way to layer like this in pygame?

后端 未结 2 412
感动是毒
感动是毒 2021-01-25 06:32

I\'ve been working on a small project in pygame. It\'s an overhead 2D game, but if a player is behind an object, I need the player to be one layer behind it. If the player is in

2条回答
  •  清歌不尽
    2021-01-25 06:46

    I tried with this code (it most likely works)

    When the red surface is behind the green the green will overlap, that's why I've kept it a little transparent. When the red overtakes it will be blitted on the green. The code is same as you did. IDK why yours doesn't work

    import pygame
    
    pygame.init()
    clock = pygame.time.Clock()
    
    screen = pygame.display.set_mode((800,600))
    
    surface1 = pygame.Surface((50,50))
    surface1.fill((255,0,0))
    
    surface2 = pygame.Surface((50,50))
    surface2.fill((0,255,0))
    surface2.set_alpha(196)
    
    surface1X = 0
    surface1Y = 275
    
    surface2X = 400
    surface2Y = 275
    
    x_change = 0
    y_change = 0
    
    speed = 2
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
    
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -speed
                if event.key == pygame.K_RIGHT:
                    x_change = speed
                if event.key == pygame.K_UP:
                    y_change = -speed
                if event.key == pygame.K_DOWN:
                    y_change = speed
    
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    x_change = 0
                    y_change = 0
    
        surface1X += x_change
        surface1Y += y_change
    
        screen.fill((255,255,255))
    
        if (surface1X < surface2X):
            screen.blit(surface1, (surface1X, surface1Y))
            screen.blit(surface2, (surface2X, surface2Y))
    
        else:
            screen.blit(surface2, (surface2X, surface2Y))
            screen.blit(surface1, (surface1X, surface1Y))
    
        pygame.display.update()
        clock.tick(60)
    

提交回复
热议问题