-1
\$\begingroup\$

Is there anyone who knows how to create an infinite verticle scrolling background in pygame?

Your help would be much appreciated, thanks in advance!

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The idea behind infinitely scrolling backgrounds is pretty simple. You simply draw the background enough many times to fill the screen, and once a piece of the background moves off screen, you loop the rendering and start back from the beginning.

So, the basic functionality would go as follows: (pseudo code, should be easily adaptable to PyGame)

piece = yourBackgroundImage;
pieceHeight = piece.h;

scrollY = 0;

for (pieceY = (scrollY % pieceHeight) - pieceHeight; pieceY < screenHeight; pieceY += pieceHeight)
{
    render(piece, 0, pieceY);
}

First, you take your background image you want to loop. You need to know it's height, as that's what we used to calculate how often we need to render it. The scrollY variable in the code above is the value you would modify in your main loop to create the scrolling effect.

Now, the loop is slightly more complicated, but not much. We start by calculating how much vertical movement there is along a single piece (scrollY % pieceHeight). We need to decrease that value by a single piece height, to make sure that the whole screen gets filled (you can try it without the decrement, and see that there will be a small piece of the background missing at the top of the screen). We will iterate as long as there is screen space to fill, and increment each step by the background image's height.

That should do it, and the algorithm is of course easily translatable to horizontal movement too.

\$\endgroup\$
2
  • \$\begingroup\$ When i tried to implement your code, I got a syntax error saying that the equal sign after "backgroundY" in "for (backgroundY = (scrollY % backgroundHeight) - backgroundHeight, backgroundY < screenHeight; backgroundY += backgroundHeight):" is a syntax error. This is my code: background = pygame.image.load(path.join(img_dir, "Backgrounds/1.jpg")).convert() backgroundHeight = background.h scrollY = 0 for (backgroundY = (scrollY % backgroundHeight) - backgroundHeight, backgroundY < screenHeight, backgroundY += backgroundHeight): render(background, 0, backgroundHeight) \$\endgroup\$ Jul 17, 2016 at 11:40
  • \$\begingroup\$ As I said, it's pseudo code. You obviously need to convert the for loop (among the rest of the code) to the Python syntax. \$\endgroup\$
    – user35344
    Jul 17, 2016 at 11:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .