Creating An Immersive Scrolling Game Background! (Part 2)
Following on from Part 1, I’ll be upgrading the system to be mostly automatic for all those finicky number calculations, and removing obvious repeating patterns!
If you haven’t read Part 1, go do that first.
Today’s Objective: Upgrade the Scrolling Background script to do most of the number calculations automatically, instead of manually.
The actual effect will remain the same, but it will be a lot easier to make it look correct after this upgrade.
I move the ForEach loops into individual functions:
Now to start the improvements:
Variables (These will be explained in detail soon):
Functions:
Create a new function called “InitializeForegroundLayerDuplicates”. Within this function we want to:
- Add the “_fgOriginalTransform” to the private List<Transform> “_fgTransforms”,
- Define a starting position for our _fgOriginalTransform copies, using the _fgXRandomRange and _fgImageHeight variables.
- Create a For loop from 0->(_fgVerticalCopies -1), which instantiates duplicates of the _fgOriginalTransform at the starting position defined above,
- And, update the starting position ready for the next copy.
In both the “Update????groundLayer()” functions:
Make sure to switch the “_??LowerLimit” variables to “-_??ImageHeight”.
Also make the X value defined when it repositions to be a random value, just like the “_??CopyPosition” does for its X value.
Now create a new Awake function:
Then in the Unity Editor:
Now, using the number of Scrolling Layers you had before deleting all but 1, decide how many layers you need in order to completely fill the Camera vertically plus at least 1 extra.
For my Foreground I use a large image so it’s 1 to fill plus 1 extra. My Background is 3 to fill plus 1 extra.
On the Scrolling Background component, set the “_??VerticalCopies” variables to this number minus 1. It will already have the original in the list, so we only need to spawn the copies (total required -1).
Now set the references.
The single Scroll Layer to the Original Transform variable, and (one of) the Sprite Renderer to the Image Size Reference variable. It is fine if you have multiple sprite GameObjects under the Scroll Layer objects. Just make sure they are all the same size, because the referenced renderer’s size is used for all reposition calculations.
The X Random Range variable is how far to the left and right from zero the repositioned Scroll Layers can be placed. By adding a random horizontal offset, you can avoid repeating patterns in the background which are easily noticed by the player.
All done!
You can see on the right side that with both layers, no obvious patters or repeating star positions are noticeable. The player will appreciate this.
I hope this helped you create a better scrolling effect! That’s all for now!
And if you somehow got this far without reading Part 1, you should probably go do that, otherwise this may have been confusing.