Is there anyone who knows how to create an infinite verticle scrolling background in pygame?
Your help would be much appreciated, thanks in advance!
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityThe 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.