1

I'm trying to get a scrolling background to work where the background image is smaller than the window of the program. For this reason, I created a for loop to move two groups of the same copied image.

The weird thing is that the two groups of images keep drifting apart instead of staying together, seamless.

This is using C++ and raylib, but after searching around I'm not sure this is a raylib specific issue.

Here is an example of how they drift apart instead of staying seamless: issue with seams issue with seams after a few minutes

Here is the code:

        #include "raylib.h"
    
    int main()
    {
        //preamble
        const int windowW{600};
        const int windowH{380};
        float dt{0};     // for use with delta time between frames
    
        SetTargetFPS(60);
        InitWindow(windowW, windowH, "walk");
    
        //backgrounds
        Texture2D bg = LoadTexture("textures/far-buildings.png"); // 256 X 192
        const float bgScale{0.5};
        const int bgQty{2};
        float bgX{0.0};
        float bgX2{(bg.width * bgScale * bgQty)};
    
        while (!WindowShouldClose())
        {
            //start drawing
            BeginDrawing();
            ClearBackground(WHITE);
    
            dt = GetFrameTime();
    
            bgX -= 250 * dt;
            bgX2 -= 250 * dt;
    
            if (bgX < -(bg.width * bgScale) * bgQty)
            {
                bgX = (bg.width * bgScale) * bgQty;
            }
            if (bgX2 < -(bg.width * bgScale) * bgQty)
            {
                bgX2 = (bg.width * bgScale) * bgQty;
            }
    
            for (int i = 0; i < bgQty; i++)
            {
                Vector2 bgPos{bgX + ((bg.width * bgScale) * i), 0.0};
                Vector2 bgPos2{bgX2 + ((bg.width * bgScale) * i), 0.0};
                DrawTextureEx(bg, bgPos, 0.0, bgScale, WHITE);
                DrawTextureEx(bg, bgPos2, 0.0, bgScale, WHITE);
            }
    
            DrawText(FormatText("dt: %f", dt), 3, windowH - 10, 10, GOLD);
            EndDrawing();
        }
        UnloadTexture(bg);
        CloseWindow();
    }

Here is the background image:

background image

user1026169
  • 5,345
  • 5
  • 21
  • 35

1 Answers1

2

You've made your code overly complex. To get repeats just make a source rectangle (UV coordinates) that are larger than the source image and OpenGL will repeat it. Set your source rectangle to be the same size as the screen and just offset the source rectangle origin as you scroll.

Here is a simple example. https://github.com/JeffM2501/TestFrame/discussions/12