Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

Your help would be much appreciated, thanks in advance!

share|improve this question

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.

share|improve this answer
    
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) – Tahmid RAhman Jul 17 at 11:40
    
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. – Tyyppi_77 Jul 17 at 11:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.