Easy Parallax Backgrounds in LibGDX

I recently needed to create a parallax background in LibGDX. I did a quick search and the methods I saw mostly relied on how you might implement parallax in other engines/frameworks (namely, drawing two textures that “leapfrog” each other and off-setting them). However I discovered that in LibGDX we can use TextureRegions and texture wrapping to do all the hard work for us.

Also keep in mind that this also works for parallax elements in the foreground, if you need some layers to be in front of the action.

The ParallaxLayer class

We’ll start by making a class that represents a “layer” of the parallax background. This will have the texture, the parallax factor (how much the camera movement should affect this layer) and whether it should repeat horizontally or vertically. We’ll also need a reference to the camera so that when the camera moves we can update this layer.

Note that we set the TextureWrap attribute on the texture. This is so when we use a TextureRegion to draw this texture, if we want it to repeat horizontally or vertically, the texture will automatically be repeated on either axis.

Next, we’ll need a render method that draws this layer:

We first calculate the offset based on the camera’s position and the factor of this layer, then we use that as the X and Y for the TextureRegion.

Next, if this layer should wrap horizontally, we set the width to be the width of the viewport (the texture will wrap around automatically if the region extends beyond the image bounds). If not, we just want the width to be the texture’s width. We do the same with the region’s height.

Finally, we draw the texture region centered on the camera.

Usage

I set up a demo scene using some parallax backgrounds I found here.

It’s important to note that the order in which the layers are in the array is the order in which they’ll be drawn. The factor should (generally) increase as you move towards the foreground as that looks most realistic, but there are cases where you might want objects in the “foreground” to move slower. Feel free to tweak these values until it looks “right”.

Finally, to render all the layers, we just loop over the array and draw each, passing a SpriteBatch to them (make sure to call batch.begin() beforehand and batch.end() after you’ve finished drawing).

I also in this demo allow the camera to be controlled with the arrow keys, you can mostly ignore this code if it doesn’t suit your usage.

And the result is a lovely parallax scene:

There’s of course more that you might want to do to adapt this method for your use case (like clamping the camera position so that it can’t go out of bounds on an axis that isn’t repeated). But I’ve found this to be a nice simple way of implementing it.

The full project can be found on Github.

Written on June 17, 2020