Animating an image going across the screen in pygame but most of the image looks…"glitchy"

Question:

I’m trying to make an image fly across the screen from the left to the right.

It moves but the background keeps cutting in so only portions of the image show and the full image appears at the end of the loop.

I did something like this once a year before but the code I was writing back then is so "spaghetti-ed" that I can’t even read or understand it.

Here’s my code now:

import pygame

screen = pygame.display.set_mode((1000, 600))
background = pygame.Surface((1000,600))

image = pygame.Surface((1000,600))
for i in range(0,100,5):
    #draw backgound
    screen.blit(background, (0, 0))
    pygame.display.update()

    #draw image
    image.blit(pygame.image.load("imageName.png"), (0,0))
    print("image position:", i-20)
    screen.blit(image, (i-20,0))
    pygame.display.update()
    
    pygame.time.delay(10)

Why is this happening? Is it my computer or is it my code? How can I fix it?

Answers:

The issue is, that image file “imageName.png” is loaded in every iteration of the loop:

for i in range(0,100,5):
    # [...]

    image.blit(pygame.image.load("imageName.png"), (0,0))

    # [...]

Load the image once and use the image in the loop

imageName = pygame.image.load("imageName.png")

for i in range(0,100,5):
    # [...]

     image.blit(imageName, (0,0))

    # [...]

Further more it is sufficient to do a single pygame.display.update() after drawing the scene:

import pygame

screen = pygame.display.set_mode((1000, 600))
background = pygame.Surface((1000,600))
image = pygame.Surface((1000,600))
imageName = pygame.image.load("imageName.png")

for i in range(0,100,5):

    #draw backgound
    screen.blit(background, (0, 0))

    # draw the scene
    image.blit(imageName, (0,0))
    screen.blit(image, (i-20,0))

    # update the display
    pygame.display.update()

    pygame.time.delay(10)

A further improvement can be achieved by using pygame.time.Clock() and .tick() rather than pygame.time.delay().. e.g:

clock = pygame.time.Clock()
x = 0
run = True
while run and x < 100:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    deltaTime = clock.tick(60)
    x += deltaTime / 25

    #draw backgound
    screen.blit(background, (0, 0))

    # draw the scene
    image.blit(imageName, (0,0))
    screen.blit(image, (x-20,0))

    # update the display
    pygame.display.update()
Answered By: Rabbid76
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.