In this article we will look at creating some parallax scrolling background layers.
In the last article we look at getting a basic SDL application up and running. The ultimate goal of this tutorial series is to create a side scrolling shoot'em'up, so with the basic framework we have already laid down it's not time to start building up the game. In this article we will look at creating some parallax scrolling background layers.
Parallax scrolling is used extensively in 2D games to give the impression of depth. It works by creating several layers, with those that represent the furthest objects scrolling the slowest. This makes it seem that these background layers are further away.
RepeatingVisualGameObject.cpp / RepeatingVisualGameObject.h
The RepeatingVisualGameObject class extends the VisualGameObject class that was created in the last tutorial. It's purpose is to draw a repeating texture with an optional offset in either the X or Y axis. The class can also modify the amount of offset is applied. By specifying that more distant objects apply a smaller fraction of the offset we can create parallax scrolling.
The width and height properties define the area that the RepeatingVisualGameObject will draw to. Previously the VisualGameObject simply drew the entire surface that it loaded. The RepeatingVisualGameObject will instead draw the tile the surface within an area that is defined the the width and height, positioned at the x and y coordinates inherited from the VisualGameObject class.
The scrollFactor property defines how much of the common scroll factor, defined in the static xScroll and yScroll properties, to apply when drawing the image. The higher the value, the more quickly a RepeatingVisualGameObject object will appear to scroll.
These values are all specified in by the various constructors. [code]
The Draw and DrawRepeat functions are where the image offsetting and tilling is calculated and drawn to the screen, taking into account the scrollFactor. In this case we also modify the xScroll property directly in the Draw function. This is just for convenience, and the code to modify the xScroll property will be moved to another class at a later point. [code]
The SetScroll function is a static function, modifying the static properties xScroll and yScroll. It's these properties that define how much all the RepeatingVisualGameObject classes will be scrolled by. [code]
ApplicationManager.cpp / ApplicationManager.h
The ApplicationManager create 3 new instances of the RepeatingVisualGameObject class, which creates 3 levels in the background. By defining different scrollFactors on each object we create the parallax scrolling effect. [code]
As you can see creating parallax scrolling is quite easy for such an cool effect.
Download the source code here.
Read more in the SDL Programming Tutorial series