Layers of Detail with Blitting in SDL

Continuing with my efforts to learn SDL, I’ve drawn kind of a silly set of bitmaps that will be sewn together to form a landscape.

To the left you see a composite of 11 distinct images.  Each image falls into one of 4 layers, Foreground, Middleground, Background, Clouds, and Horizon.

The point of having multiple layers is to simulate depth in a simple side-scroller.  The “closer” the layer is to the user, the faster it’ll slide across the screen.  In the case of the “Clouds” layer, it has a slow but constant motion of its own.  In my simple tileset, I imagine the player to be somewhere in between the “Foreground” represented by the green/orange things stuck to the bottom of the screen and the “Middleground” which are the bent looking rectangular structures in the middle of the image.

For the programming part of this exercise, I’ve been simply following this SDL Tutorial.  That tutorial basically gets you a class that manages the lifecycle of your game along with the main() method.  I had a little bit of trouble getting this to work in OSX, but it turned out that I simply needed to RTFM.  If you’re trying this on a Mac, be sure to copy SDLMain.h and SDLMain.m from the “Extras” folder in the .dmg.

The lion’s share of the work in this SDL_BlitSurface(). This method is well described in the second SDL TutorialBlitting is really just the act of drawing one bitmap on top of another.

To implement layers as described above, I’ll create a class called an ImageLayer which takes an array of SDL_Surface objects (images) and an array of coordinates representing the upper left corner of each instance of the image sorted by X coordinates.  As the layer gets scrolled left or right, it’s a simple matter of keeping track of which image instances represent the extreme edges of what’s visible. All images in between these extremes get rendered.

With multiple ImageLayers populated with images and where they are, you render each layer from furthest to nearest.