Lag When Win.Blit() Background Pygame

Pygame - blit is causing lag

Ensure that the background Surface has the same format as the display Surface. Use convert() (or convert_alpha()) to create a Surface that has the same pixel format. This improves performance when the background is, when the background is blit on the display, because the formats are compatible and blit does not need to perform an implicit transformation.

bg_surf = image.load('assets/PNG/Backgrounds/set1_background.png').convert()
bg1Colour = bg1Colour = transform.scale(bg_surf, (1280, 1024))

Why does my game made with Pygame suddenly lag for a few seconds?

Call convert() on the background image. That ensures that the image has the same pixel format as the display Surface and will help blit to operate with optimal performance:

screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png').convert()

Note, if the surface has a different format than the display, then blit has to convert the format on the fly in every frame.

Random lag spikes with pygame parallax background

Do not load the images in the application loop. Loading an image is very time consuming because the image file has to be read and interpreted. Load the images once at the begin of the application:

# Background class
class Background(pygame.sprite.Sprite):
def __init__(self, image, x):
super(Background, self).__init__()
self.surf = pygame.transform.smoothscale(image, (s_width, s_height))
self.rect = self.surf.get_rect(center=(x, s_height/2))
bg_img_filelist = ["layer1.png", "layer2.png"]
bg_img_list = [pygame.image.load(f).convert_alpha() for f in bg_img_filelist ]
l1 = Background(bg_img_list[0], s_width/2)
l2 = Background(bg_img_list[1], s_width/2)


Related Topics



Leave a reply



Submit