Skip to content
Advertisement

Pygame : player sprite that disappears behind the background

So there you go, I wanted to experiment a little pygame but I find myself stuck.

Context

I created a small sprite (with Piskelapp) that represents the player and looks like:

player.png

player.png

then add my background in jpg format. However when launching the game, my sprite is cut by the background as follows:

bg and player.png

The ship is not placed in front of the background and more I go up it, more it disappears behind the background…

Here is my code:

import pygame
pygame.init()

# class user

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.pv = 100
        self.__max_health = 100
        self.attack = 2
        self.velocity = 5
        self.image = pygame.image.load('assets/player.png')
        self.rect = self.image.get_rect()
        self.rect.x = 400
        self.rect.y = 500

# open game window
pygame.display.set_caption("Rocket 'n' Rock")
screen = pygame.display.set_mode((1080, 720))

# background import
bg = pygame.image.load('assets/bg.jpg')

# load player

player = Player()

running = True

# game mainloop
while running:

    # bg apply
    screen.blit(bg, (0,-400))
    # screen update
    pygame.display.flip()

    # player image apply
    screen.blit(player.image, player.rect)

    # if player close the window
    for event in pygame.event.get():
        # *close event
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            print("close game")

anyone have a tip? I’m wondering if it’s not a file format problem? thank you for your time

Advertisement

Answer

In you game mainloop, you should put:

screen.blit(player.image, player.rect)

before:

pygame.display.flip()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement