Last week, I implemented a scrolling background into our game to give the sense of movement that the player plane was flying forward.
The scrolling code was very simple to do using only 2 background objects. How it worked was you set the speed and direction you wanted the GameObject to move then once it reached a certain point, it would look back up to its original position and repeat. In this case, the certain point was the length of the Sprite so as soon as the GameObject had moved it’s own length, it would then set the position back to it’s original one. The use of Mathf.Repeat helped simplify the movement code as it ensured a value was kept within a certain range and if it went beyond that range, it would loop back around to the start and add the difference on.
The code is simple, robust and is easy to read so I am happy with it. Using the y size of the Sprite means this script can be easily added onto any other GameObject with a SpriteRenderer and have that be used as a scrolling object without needing to calculate the length of it in Unity’s world units. Although there isn’t a specific I would improve this script, I would like to improve the background scrolling system overall. This would be done by allowing some randomness so the surface underneath you doesn’t feel as repetitive as different background sprites would be used. The sprites could also be randomly offset along the x axis too, to give more variance to the terrain.