Parallax with tiling sprites

If you’re using the background sprites included in the pre course assets, you’ll notice that they don’t extend the length of the screen once we’ve added the parallax effect. One way to change this without needing to an image editing program is to use tiling sprites. It requires a little bit of setup:

First, go to the background sprite file(s) and change Mesh Type to Full Rect then Wrap Mode to Repeat (and remember to push Apply afterward!)

Next, in the sprite renderer change Draw Mode to Tiled which will show options for Width and Height. We’ll need to increase the width for the sprite to display properly, in this example I multiplied it by 4.


After that, in the Parallax script we can add some extra code to use this alternate method. I left in the original code so both ways can be used from one monobehaviour. (All new lines of code have a comment beside them.)

using UnityEngine;

public class Parallax : MonoBehaviour
    [SerializeField] float _parallaxOffset = 0.9f;
    [SerializeField] bool _useTiledSprite = false; // Whether we want to use the course's version or the tiled sprite version

    Vector2 _startPosition;
    Vector2 _startSize; // The size of the sprite at the start of the scene
    Vector2 _travel => (Vector2)_mainCamera.transform.position - _startPosition;

    Camera _mainCamera;
    SpriteRenderer _spriteRenderer; // Reference to the Sprite Renderer

    void Awake()
        _mainCamera = Camera.main;
        _spriteRenderer = GetComponent<SpriteRenderer>(); // Getting the Sprite Renderer

    void Start()
        _startPosition = transform.position;
        _startSize = _spriteRenderer.size; // Setting the correct starting values for the Sprite Renderer's Width and Height

    void FixedUpdate()
        if(!_useTiledSprite)                                                                // The behaviour used in the course
            Vector2 newPosition = _startPosition + new Vector2(_travel.x * _parallaxOffset, 0f);
            transform.position = new Vector2(newPosition.x, transform.position.y);
        else                                                                                // The alternate, added behaviour
            Vector2 newSize = _startSize + new Vector2(_travel.x * _parallaxOffset, 0f);    // Using the starting size as a reference, we get an offset value for Width (x)
            _spriteRenderer.size = new Vector2(newSize.x, _startSize.y);                    // The Sprite Renderer's Width is changed by our calculated offset


For background 3 I used a _parallaxOffset value of 0.5, for background 4 I used 0.8

Privacy & Terms