So this week (cough cough, last night and today) I’ve been working on implementing the background assets that Lethe was kind enough to prepare for me. To be honest, it was much easier than I expected. It took far less time to do and was much smoother than I’d expected.
The Parallax Effect
So pretty much any scrolling game with 2D backgrounds will use some sort of parallax effect. This means that the background is made up of layers and each layer scrolls at a different rate relative to the camera. It gives the background a sense of depth because things “closer” to the camera move by faster just like in real life.
It’s a pretty good way to instantly make a background look 10x more polished. Previous engines I’ve worked with have had built in parallax tools since it’s basically a necessity for 2D. Unity, being only vaguely aware that 2D games exist, has no such built in support. I knew roughly how to do it, you just make game objects for each layer of the background and then use a script to set their position to some percentage of the camera’s position. I was mainly worried about how such a system would interact with the existing camera lerp.
Camera Lerp
A “lerp” (short for linear interpolation) is a function that returns a value between two other values based on some scaling factor. So you give it a start point, A, an end point, B, and then a value between 0 and 1 to interpolate by, let’s call it T. If T = 0.5, it will return the exact midpoint between A and B.
For example, if A = 10 and B = 20, then T = 0.5 would return 15 and T = 0.1 would return 11. This is a useful function for, again, making backgrounds and scrolling look more polished. The camera tracks the player, since that’s what you need to see. What I can do is have that tracking lerp between where the camera currently is and where the player currently is and it will make the camera sort of slide over to the player rather than instantly snapping on. It means the player will be just a little out of center when they move, which looks nice and helps give a feeling of momentum and weight.
With parallax, I was a little worried about how the two systems would interact, but because they are each manipulating the positions of different objects, they can work independently of each other. The lerp is on one object (descriptively named “CameraThingy”) and then the parallax is on a child of that object. In Unity, a “child” object will always follow the position, rotation, and scale of it’s parent, with its own transform just being relative to the parent. So the parallax works and the whole thing follows the player on a lerp!
Conclusion
Sometimes it just works perfectly on the first try and you don’t need to bang your head against a wall for hours trying to fix it. I like those times. The parallax script is only around 20 lines and could be even shorter if I wanted.
Sorry for being a day late, but I was very busy yesterday. Anyway, see you next Thursday.
-S