Making the background move sideways in pygame

If you want to have a continuously repeating background, then you’ve to draw the background twice:

        +==================+
   +----||---------+------||------+
   |    ||         |      ||      |
   |    ||    1    |   2  ||      |
   |    ||         |      ||      |
   +----||---------+------||------+
        +==================+

You’ve to know the size of the screen. The size of the height background image should match the height of the screen. The width of the background can be different, but should be at least the with of the window (else the background has to be drawn more than 2 times).

bg_w, gb_h = size
bg =  pygame.transform.smoothscale(pygame.image.load('background.image'), (bg_w, bg_h))

The background can be imagined as a endless row of tiles.
If you want to draw the background at an certain position pos_x, then you have to calculate the position of the tile relative to the screen by the modulo (%) operator. The position of the 2nd tile is shifted by the width of the background (bg_w):

x_rel = pos_x % bg_w
x_part2 = x_rel - bg_w if x_rel > 0 else x_rel + bg_w

Finally the background has to be blit twice, to fill the entire screen:

screen.blit(bg, (x_rel, 0))
screen.blit(bg, (x_part2, 0))

You can test the process by the following example program. The background can be moved by <- respectively ->

import pygame

pygame.init()

size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

bg_w, bg_h = size 
bg = pygame.transform.smoothscale(pygame.image.load('background.image'), (bg_w, bg_h))
pos_x = 0
speed = 10

done = False
while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    allKeys = pygame.key.get_pressed()
    pos_x += speed if allKeys[pygame.K_LEFT] else -speed if allKeys[pygame.K_RIGHT] else 0

    x_rel = pos_x % bg_w
    x_part2 = x_rel - bg_w if x_rel > 0 else x_rel + bg_w

    screen.blit(bg, (x_rel, 0))
    screen.blit(bg, (x_part2, 0))

    pygame.display.flip()

Leave a Comment