PyGameExamplesAndAnswers

StackOverflow            reply.it reply.it


Background

Checkered background

Related Stack Overflow questions:

Scale background

Scroll background

Related Stack Overflow questions:

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))

Parallax background

Related Stack Overflow questions:

Background scrolling is achieved by moving the background image. The image is drawn into the window with an offset and must be drawn twice:

def draw_background(surf, bg_image, bg_x, bg_y):
    surf.blit(bg_image, (bg_x - surf.get_width(), bg_y))
    surf.blit(bg_image, (bg_x, bg_y))

For a background parallax effect, you need several background layers that you must move at different speeds. The back layers must be moved more slowly than the front layers. e.g.:

bg_layer_1_x = (bg_layer_1_x - move_x) % 600
bg_layer_2_x = (bg_layer_2_x - move_x*0.75) % 600
bg_layer_3_x = (bg_layer_3_x - move_x*0.5) % 600

How to make parallax scrolling work properly with a camera that stops at edges pygame