Adding Parallax scrolling to your XNA code

Written by Dean Edis.

In our previous article we covered how we can write a simplified Photoshop-style API for displaying multiple textures on the screen.

In this article we will develop the code further to allow parallax scrolling. Parallax scrolling is used widely in games, and is useful for causing objects in a 2D scene to appear ‘distant’ by making them scroll at a slower rate than those ‘in front’.

To do this we build on our existing Layers class, as in principle we want to create a single ‘layer-able’ object containing multiple overlaid textures, creating ParallaxLayer.

For example:

First we need to allow the position of a Layer to be set. That’s easy enough - We just add a Vector2 Layer.Origin property and use this value in the TextureLayer.Draw(...) code:

public override void Draw(SpriteBatch spriteBatch)

{

 spriteBatch.Draw(m_texture, Origin, CreateWhite(ActualOpacity));

}

Then, when calling ParallaxLayer.Update(...) we scale the Origin of each Layer according to a preset amount:

public override void Update(GameTime gameTime)

{

 foreach (var layerInfo in m_layerInfos)

 layerInfo.Layer.Origin = Origin * layerInfo.MovementFactor;

 

 base.Update(gameTime);

}

 

When adding each layer to the ParallaxLayer object we also set the movementFactor value (typically in the range of 0.0f to 1.0f).

In the example code we use these values:

// Create a Layers object, and define the order of the layers to display.

m_rootLayers = new ParallaxLayer();

m_rootLayers.Add(cloudsLayer, 0.2f);

m_rootLayers.Add(mountainsFarLayer, 0.6f);

m_rootLayers.Add(mountainsNearLayer, 1.0f);

...to create a scene looking like this:

The scene can be scrolled using the arrow keys to show how each Layer moves relative to the others.

I hope you find the code useful!

DOWNLOAD SOURCE