Scrolling PNG background not working

I am a noob to linux, c++ and sdl2. I a trying to write a game. I am starting with a scrolling background. I got the code of google gemini. When I run it I just get a transparent window instead of a scrolling background. can someone please show me how to fix this?

I have:

#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
#include

int main(int argc, char* argv){
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_PNG);

SDL_Window* window = SDL_CreateWindow(“Scrolling background”, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,800,600,0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

SDL_Texture* texture = IMG_LoadTexture(renderer,“spacebackground.png”);
int texW = 0, texH = 0;
SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);

SDL_Rect destRect = {800,200,texW,texH};
int scrollSpeed = 5;

bool quit = false;
SDL_Event e;

while(!quit)
{
while(SDL_PollEvent(&e))
if(e.type ==SDL_QUIT) quit = true;
}

destRect.x -= scrollSpeed;

if(destRect.x + destRect.w < 0)
{
destRect.x = 800;
}

SDL_RenderClear(renderer);
SDL_RenderCopy(renderer,texture,NULL,&destRect);
SDL_RenderPresent(renderer);

SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();

return 0;

}

Thanks

You need to step through the code and make sure you understand every line. Look it up if you don’t. After you understand what the code does you’ll be in a better position to figure out why it’s not working. :wink:

If you don’t know SDL yet you might want to start checking out Lazy Foo’s SDL tutorials.

1 Like

Vibe coding in its essence—we have the code, but we don’t know what it does or how it work, help! Unfortunately, you won’t be able to write anything that way, so start by learning how to program, then how to use SDL, and finally how games work and how to program them. See you in a few years.

In summary, learn to code first, and use AI at most to speed up your learning—not to generate code, because without the knowledge, you won’t understand it anyway.


The main loop is incorrect because it should not only process events, but also update the logic and render frames. In the code vomited by Gemini, the main loop waits indefinitely for an exit event, and in the meantime, it burns up the CPU as long as the flag keeps the loop alive, doing nothing else.