genfy
genfy

Reputation: 83

SDL Infinite Tile Background

I'm trying to create a tiled background in SDL, one that scrolls and continues to scroll indefinitely.

So, I came up with some code and tested it out. It works well enough, but only can travel 1920 pixels along the x axis and 1080 along the Y.

Here's my code:

void Background::render(SDL_Renderer *renderer){
    int Xoffset = 0;
    int Yoffset = 0;
    for(int y = 0; (y * 411) < 1080; y++){
        for(int x = 0; (x * 405) < 1920; x++){
            Xoffset = 0;
            Yoffset = 0;
            if(GameManager::GetInstance().getGlobalX() + (405 * x) + 405 < 0){
                Xoffset = 1920;
            }
            if(GameManager::GetInstance().getGlobalY() + (411 * y) + 411 < 0){
                Yoffset = 1080;
            }
            SDL_Rect backRect = {GameManager::GetInstance().getGlobalX() + (405 * x) + Xoffset, GameManager::GetInstance().getGlobalY() + (411 * y) + Yoffset, 405, 411};
            SDL_RenderCopy(renderer, ResourceManager::GetInstance().getTexture("background"), 0, &backRect);
        }
    }
}

The getGlobalX() and getGlobalY() are where the object should be relative to the player.

Upvotes: 0

Views: 1431

Answers (1)

ChemiCalChems
ChemiCalChems

Reputation: 643

You should be able to draw the 1920x1080 background more than once.

The algorithm would look something like this.

  1. Draw a background starting at (-1920,0) (completely out of the screen)
  2. Draw another copy of the background, this time starting at (0,0).
  3. Every frame, draw both backgrounds one pixel to the right, so you'll have a scrolling illusion, the end of the background exiting the right will come out from the left.
  4. Once your background at step 1 has come to (0,0), draw another background at (-1920,0) and keep scrolling.

So basically, you push two backgrounds to the right and keep putting one on the left every time you need to. This should be simple to code.

Upvotes: 2

Related Questions