A parallax effect is a great way to add depth to your game — literally. It will help create the atmosphere in your game and draw the player into the world you have created.
What is parallaxing?
For those unfamiliar, parallaxing is when multiple layers in a 2D scene move at a different speed to give the effect of depth.
For example, imagine a 3D scene with a foreground of a grass floor and a background scene of a forest. Like in the handy example below:
When you move from left to right, the trees in the forest will move slower than the grass because its farther away. This is what parallaxing does, but in two dimensions.
The math of parallaxing
How do we achieve this in Unity? By design an orthographic (2D) camera does not render depth, which means you can’t simply increase the relative z distance between your layers and expect them to appear closer/farther. What is the solution? Move the sprite with the camera, but slower or faster depending on how “far” it is from the camera.
“By golly, if all I have to do is move an object, this should be super easy!”, you say? That’s because it is!
First we need to define some variables. camera is self-explanatory, you assign the camera object to it. speedCoefficient is what percent to slow down or speed up when the camera moves, and finally lastpos just holds the position of the camera in the last frame.
Next, the actual math part.
In the first line of the function, we change our transform.position by the how much the camera moved from the last frame to now, adjusted by the speedCoefficient. For example if we have a speedCoefficient of 0.5, the background would move at 50% the speed of the camera.
Added together, we have a beautifully working parallaxing script that can be added to any sprite you want to parallax. Note that we set the lastpos to the cameras current position in the start function.