SDL image disappears after 15 seconds

1k views Asked by At

I'm learning SDL and I have a frustrating problem. Code is below.

Even though there is a loop that keeps the program alive, when I load an image and change the x value of the source rect to animate, the image that was loaded disappears after exactly 15 seconds. This does not happen with static images. Only with animations. I'm sure there is a simple thing I'm missing but I cant see it.

void update(){
    rect1.x = 62 * int ( (SDL_GetTicks() / 100) % 12); 
    /* 62 is the width of a frame, 12 is the number of frames */
}

void shark(){

    surface = IMG_Load("s1.png");
    if (surface != 0){
        texture = SDL_CreateTextureFromSurface(renderer,surface);
            SDL_FreeSurface(surface);
    }

    rect1.y = 0;

    rect1.h = 90;
    rect1.w = 60;

    rect2.x = 0;
    rect2.y = 0;

    rect2.h = rect1.h+30; // enlarging the image
    rect2.w = rect1.w+30;

    SDL_RenderCopy(renderer,texture,&rect1,&rect2);
}

void render(){
    SDL_SetRenderDrawColor(renderer, 0, 0, 100, 150);
    SDL_RenderPresent(renderer);
    SDL_RenderClear(renderer);
}

and in main

   update();
   shark();
   render();

SDL_image header is included, linked, dll exists. Could be the dll is broken?

I left out rest of the program to keep it simple. If this is not enough, I can post the whole thing.

2

There are 2 answers

4
Benjamin Lindley On BEST ANSWER

Every time you call the shark function, it loads another copy of the texture. With that in a loop like you have it, you will run out of video memory quickly (unless you are calling SDL_DestroyTexture after every frame, which you have not indicated). At which point, you will no longer be able to load textures. Apparently this takes about fifteen seconds for you.

If you're going to use the same image over and over, then just load it once, before your main loop.

3
aslg On

This line int ( (SDL_GetTicks() / 100) % 12);

SDL_GetTicks() returns the number of miliseconds that have elapsed since the lib initialized (https://wiki.libsdl.org/SDL_GetTicks). So you're updating with the TOTAL AMOUNT OF TIME since your application started, not the time since last frame.

You're supposed to keep count of the last time and update the application with how much time has passed since the last update.

Uint32 currentTime=SDL_GetTicks();
int deltaTime = (int)( currentTime-lastTime );
lastTime=currentTime; //declared previously

update( deltaTime );
shark();
render();

Edit: Benjamin is right, the update line works fine. Still using the deltaTime is a good advice. In a game, for instance, you won't use the total time since the beginning of the application, you'll probably need to keep your own counter of how much time has passed (since you start an animation).

But there's nothing wrong with that line for your program anyhow.