I'm trying to implement Parallax scrolling in two dimensions using SDL, but I've run into an issue using SDL_BlitSurface()
to blit my layer images to the screen buffer.
The images I'm using for this are borrowed from http://en.wikipedia.org/wiki/Parallax_scrolling, and I was able to get it working fine just scrolling along the X axis, using the following code:
void Parallax::Draw(SDL_Surface* buffer) {
//draw each layer starting with the bottom
std::vector<ParallaxLayer*>::iterator it;
for(it=layers.begin(); it != layers.end(); it++){
ParallaxLayer* layer = (*it);
layer->x_offset %= buffer->w;
int draw_x = layer->x_offset - layer->image->w;
SDL_Rect blitrect = buffer->clip_rect;
while(draw_x <= buffer->w) {
blitrect.x = draw_x;
SDL_BlitSurface(layer->image, &(layer->image->clip_rect), buffer, &blitrect);
draw_x += layer->image->w;
}
}
}
This works.
Now, I've tried to adapt this into two dimensions. Here's the draw method I'm using now:
void Parallax::Draw(SDL_Surface* buffer) {
//draw each layer starting with the bottom
std::vector<ParallaxLayer*>::iterator it;
for(it=layers.begin(); it != layers.end(); it++){
ParallaxLayer* layer = (*it);
//resize offset so as not to overflow ints or whatever
layer->x_offset %= buffer->w;
layer->y_offset %= buffer->h;
int draw_x = layer->x_offset - layer->image->w;
int draw_y = layer->y_offset - layer->image->h;
SDL_Rect blitrect = buffer->clip_rect;
while(draw_x <= buffer->w && draw_y <= buffer->h) {
blitrect.x = draw_x;
blitrect.y = draw_y;
SDL_BlitSurface(layer->image, &(layer->image->clip_rect), buffer, &blitrect);
if(draw_x <= buffer->w)
draw_x += layer->image->w;
if(draw_y <= buffer->h)
draw_y += layer->image->h;
}
}
}
I've added the logic for blitting a layer that's moving in the vertical axis, but when I tested it, this just doesn't play nice. Areas of the screen end up not being blitted, which causes a lovely un-drawn effect:
Link to image as I can't post them directly (new user): SDL blitting bug example
Just to be clear, the images themselves are pushed around in another method. The front two layers are moving along the horizontal axis with varying velocity, and the background is moving vertically with a fixed velocity and horizontal with a variable velocity, but that's largely irrelevant as it's my blit function which is bugged.
It looks like I'm not re-drawing the area of the screen that has the repeating image on it, but I'm lost as to how to go about this.