Implementing scrolling backgrounds using image blitting is a common technique in 2D games. The basic idea is to create an illusion of movement by shifting the position of the background image each frame. Here's how you can implement this using SDL2:
The key is to blit the background image twice, side by side. As you shift the image, you'll wrap around to the beginning when you reach the end. This creates a seamless scrolling effect.
Let's create a ScrollingBackground
class to encapsulate this functionality:
#include <SDL.h>
#include <string>
class ScrollingBackground {
public:
ScrollingBackground(std::string File,
SDL_Renderer* Renderer)
: Renderer{Renderer}, ScrollSpeed{2} {
SDL_Surface* Surface{
SDL_LoadBMP(File.c_str())};
if (!Surface) {
// Handle error
}
Texture = SDL_CreateTextureFromSurface(
Renderer, Surface);
SDL_FreeSurface(Surface);
SDL_QueryTexture(Texture, nullptr, nullptr,
&Width, &Height);
}
void Update() {
ScrollOffset -= ScrollSpeed;
if (ScrollOffset <= -Width) {
ScrollOffset = 0;
}
}
void Render() {
SDL_Rect FirstPart{
ScrollOffset, 0, Width - ScrollOffset,
Height};
SDL_Rect FirstPartDest{
0, 0, Width - ScrollOffset, Height};
SDL_RenderCopy(Renderer, Texture,
&FirstPart, &FirstPartDest);
if (ScrollOffset > 0) {
SDL_Rect SecondPart{
0, 0, ScrollOffset, Height};
SDL_Rect SecondPartDest{
Width - ScrollOffset, 0, ScrollOffset,
Height};
SDL_RenderCopy(Renderer, Texture,
&SecondPart,
&SecondPartDest);
}
}
~ScrollingBackground() {
SDL_DestroyTexture(Texture);
}
private:
SDL_Renderer* Renderer;
SDL_Texture* Texture;
int Width, Height;
int ScrollOffset{0};
int ScrollSpeed;
};
To use this class in your main game loop:
int main() {
// SDL initialization code...
ScrollingBackground Background{
"background.bmp", Renderer};
bool Running{true};
while (Running) {
// Handle events...
Background.Update();
SDL_RenderClear(Renderer);
Background.Render();
// Render other game objects...
SDL_RenderPresent(Renderer);
}
// SDL cleanup code...
}
This implementation creates a horizontal scrolling effect. You can modify the ScrollSpeed
to control how fast the background moves. For vertical scrolling, you would adjust the y-coordinates instead of x-coordinates in the Render()
 function.
Remember to handle potential errors when loading the image and creating the texture. Also, ensure your background image is designed to tile seamlessly for the best effect.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to load, display, and optimize image rendering in your applications