According to the Wikipedia definition, parallax scrolling is a technique in computer graphics and web design, where background images move by the camera slower than foreground images, creating an illusion of depth in a 2D scene and adding to the immersion.
Well, it's pretty self-explanatory.
There are different ways in which we can achieve parallaxing in Unity. I'm going to show you my favourite approach, which involves using two cameras.
First thing first. We need to create a second camera. To make it easy, we can duplicate the camera in the scene. DO NOT FORGET to remove the Audio Listener component from one of the cameras or Unity will start screaming at you. One camera is set to Orthographic, the other one to Perspective. Then, we create an empty game object and we child both cameras to it. Both cameras must be set to Position 0,0,0, so they will be perfectly aligned with the parent object (Fig 1 - Fig 2).
Fig 1 |
Fig 2 |
Fig 3 |
Fig 4
|
Fig 5 |
By placing each one of them next to a copy of itself we can create a sort of chain.
We place both chains in two different empty object, so we can then adjust the Z value by simply moving the parent object (Fig 6, Fig 7). A very important thing to remember is to change the layer for the mountain sprites to Background, so they will be rendered only by the perspective camera. Also, the sorting layer. Even though we are working with a perspective camera, sorting layers still matter when using sprites, therefore, the chain of mountain that we want to keep in the front (in our case, the "brown one", needs to have all its sprites with a sorting layer higher then the other mountain chain). By doing so, we make sure that the front mountain chain is always drawn on top of the other one. (Fig 6, Fig 7).
Fig 6 |
Fig 7 |
At this point we play around with the Z value and the scaling of the 2 parent objects of the mountain chains (BackChain - FrontChain in Fig 6 and Fig 7) until we are satisfied with the result. It is important to notice that we should keep watching the Game window to observe the result, as that is where we'll see the perspective camera creating the depth effect. In the end we should end up with something like this:
Well, that is pretty much it. If we want to add more background scrolling objects, all we have to do is to assign them to the layer Background, adjust the sorting layer of the sprite renderer and place them in the scene. All the background object will be rendered by the perspective camera, which takes in consideration the Z value of the transform, giving a sense of depth. The rest of the level, like interactable objects and units (chests, enemies) can be placed on other layers and be rendered by the orthographic camera and be on the same "plane" as the player.
Example scene here.
No comments:
Post a Comment