A parallax Background consists of multiple background objects that seem to be visually in distance from each other. They create an illusion of the background following the viewer in varying speeds when the camera is moved left or right.
In this tutorial, we will group objects into three different parallax layers. These include Background, Midground and Foreground parallaxes.
During this lesson, we will be following a tutorial video on structuring a parallax background. We will learn how to set up the assets in Unity, drag and drop them into the Unity hierarchy, set the distance for each asset and create an infinite scrolling background.
You are free to use whatever 2D assets you have, either from a free Unity Asset Store package or perhaps ones you have made yourself.
First, let us open Unity and export the art assets, after which we will drop and sort them into the hierarchy.
If you wish to use art assets from the Asset Store, you can download them into your project via Project Manager.
The 'Midground Parallax' includes assets we can see in the vicinity but that are not in our immediate range. These include, for instance, trees and clouds.
The 'Foreground Parallax' includes the objects we physically interact with or are close to, like platforms.
Add your background assets by dragging them inside the parent objects.
Your hierarchy is now set up! At this point, you should have a hierarchy consisting of three parallax parents and background assets inside them.
Just like in real world, using Background Parallaxes adds a realistic feeling to your environment as the objects appear to move in different speed in correlation to your movement.
Unity has an option to set the selected asset into a specific distance from the camera. This option is called "Order in Layer". The bigger the layer number is, the closer it is to the camera, and vice versa. When designing a parallax background, we use this setting to create the wanted background effect.
Select an asset in one of your parallax parents. See Inspector and select Order in Layer under Additional Settings.
Remember that the smaller the number in 'Order in Layer' is, the closer it is to the camera.
The games rarely focus on constrained window because we want to explore the world with our character. We can reuse the background infinitely by creating a background loop.
To create the effect, let us move on to complete the following steps in this tutorial.
Once you have written the script from the tutorial video, drag and drop it on all three 'Parallax' parents. Remember to assign your main camera into the "Cam" section.
Duplicate the 'Background' parent twice and drag them on the X axis on both sides of the original asset hierarchy.
Finally, press Play to witness the results by dragging your main camera on the X axis. Witness how the parallaxes move in correlations to each other!
Next, we will learn how to use the 2D Animation Tool in Unity.