How To Blit Animated Backgrounds With Sdl?


KeimOmatiC said:
Hi.
I have a few animated sprites which should appear in the background of my level at fixed positions.
Problem is, that the level is bigger than the screen and i don't know how to blit the sprites correctly.

Blitting directly to the screen didn't work, because the sprites don't leave the visible area, when they reach the visible area (seems as if every SDL_Rect based position on the *screen which is at x or y < 0 is set to position = 0).

01.png


As you can see, the flowers never left the visible area

02.png


Blitting to another surface fixed the problem with the leaving of the visible area but since there is no double buffer every step of the animation is drawn to the same surface.

03.png


So, what I need is a surface with the size of the level (again: bigger than the visible area) where I can use the blit & flip technique or something which can archive the same effect.

Any help ist appreciated, thanks in advance.
On each cycle, for each flower, check whether the flower is in the visible area or not. If not, don't blit it at all. Another idea is to use a surface bigger than the screen but it would be waste of resources.
 
Last edited by a moderator:
First, after initializing the screen, write:

CODE
SDL_SetClipRect(screen, NULL);


Now, the SDL docs say that the screen destination rect gets clipped after every call to SDL_BlitSurface, hence why any negative coordinate becomes 0. To avoid this, don't store your sprite's coordinates in a SDL_Rect, store them in some int x, int y, and pass them as a new destination rect for every blit:

CODE
SDL_BlitSurface(spriteData, NULL, screen, &(SDL_Rect){x, y});
 
Give this a try, maybe the compiler likes it better:

CODE

SDL_Rect temp = {myLevel.BG1.x, myLevel.BG1.y};

SDL_BlitSurface(myLevel.BG1.BG_gfx, &myLevel.BG1.Frame[0], screen, &temp);
 
1. create the virtual world, give all objects virtual world coords.
2. create a screensize viewport rectangle and initialize everything.

With all the flowers[] in an array loop through them to see if any are within the viewport and if so draw them at flower[ i ].x - vport.x.
 
You need a function that creates a background from tiles (I assume you already have this).

You would also need some kind of animation system. One that cycles through frames at a given speed.

Then you scan through the part of the map that is being displayed. If you find a tile that needs to be animated, pass it to the animation system and let it figure out what tile it actualy needs to display at that given time.

I am planning on implementing this in my own background functions later.

The upside of this is that it confines the animation to the background code, and doesn't make a mess of your sprite-usage.

The downside is that if every tile on screen is animated, it will have to update the entire part that is displayed, but that is pretty much unavoidable anyway.
 
Back
Top