Search code examples
2d-games

game Background scrolling/looping algorithm


A few months ago when i was making 2D background scrolling game i needed to make a background loop making it seem like the game character is moving , so i used the following algorithm to loop the background->

    int w=backgroundImage.getWidth();
     int h=backgroundImage.getHeight();
     int desX,desY;

     for(int x=0;x<w;x++)
     {
         for(int y=0;y<h;y++)
         {
             int px=backgroundImage.getRGB(x, y);

             desX=x-2;
             desY=y;


             if(desX<0)
             {
                 desX=w+desX-1;

             }

             backgroundImage.setRGB(desX, desY, px);
         }



     }

but after applying this algorithm to loop the whole background, i found that the whole game getting slow .

Is this algorithm any good or are there more better algorithms for looping the background??

Any code snippets would be highly appreciated.
Thanks.


Solution

  • Depending on the language used this method could easily cause the performance drop you're noticing. I suggest working with the draw offset of the background image instead of trying to change the raw pixel data itself.

    Firstly, make a background image wider than the game's viewport. During each update cycle move the image by x pixels (x depends on the speed of movement you want to portray).

    Also, let's assume you move the BG to the left. As you keep moving to the left, the right edge of the image will come into the viewport and you'll notice a black band expanding from the right edge of the viewport. To prevent this artifact, you'll need to be drawing TWO background images side-by-side.

    Also, to make it all look seamless you'll have to obviously design to BG images to tile that way. As you might expect this method will be much faster than the existing snippet.