Now that we have the beginnings of a game framework, let’s do something fun with the canvas element.
Parallax scrolling is a term used to describe a technique where several layers are transposed on top of each other, with those in the background scrolling more slowly then those in front. This creates the illusion of depth, and is used extensively in 2D games.
The RepeatingGameObject class allows an image to be repeated and scrolled inside a defined area. Up until now we have been drawing an image in it’s entirety. RepeatingGameObjectis different in that it takes an image and draws it such that it fills up an area that has been defined (the dimensions of which are independent of that image that is being drawn). We will use this to take a large image (like a panoramic mountain view) and display just a small section of it at a time to create a background image.
You may have noticed the xScroll and yScroll properties of the GameObjectManager, which are passed to the draw and update functions on the GameObjects. These values define how much the camera has been moved along the x and y axes. The RepeatingGameObject class uses these values to scroll the texture they display, creating the illusion of movement.
First we need to define the area that the RepeatingGameObject will draw to. The x and y properties of the underlying GameObject class define the top left position, while the new width and height properties define the size of the drawing area. [code]
The scrollFactor property is used to change the amount of scrolling that is reflected in the RepeatingGameObject object in regards to the xScroll and yScroll values passed to the draw function. By setting scrollFactor to a value less than one we get slower movement, and thus the illusion of a more distant object. [code]
The draw and drawRepeat functions do the hard work of actually rendering the tiled and offset texture. [code]
Here we use the ApplicationManager to create three new instances of the RepeatingGameObject class. Each is used to display a new parallax layer, using the z (depth) and scrollFactor values to create progressively deeper and slower moving RepeatingGameObject instances.
The end result is quite convincing. The parallax scrolling gives a nice sense of depth, and the whole effect has been achieved with one additional class.
This tutorial series shows you how to make an old school shoot’em’up with C++ and SDL.
- An Introduction to the Canvas Element
- Advanced Image Manipulations with the Canvas Element
- Parallax Scrolling with the Canvas Element