2D Scrolling Backgrounds

Checked with version: 4.5

-

Difficulty: Intermediate

Scrolling Background can really help sell a 2D game and keep the performance high and the code efficient. In this session we will look as various ways to move and scroll backgrounds, create the feeling of parallax and look at ways to efficiently manage the assets and code. Tutor: Adam Buckner

2D Scrolling Backgrounds

Intermediate 2D Game Creation

Download the project images HERE.

Please note that "Done_BGScroller" can be found in the Space Shooter tutorial in the context of the completed game.

Done_BGScroller

Code snippet

using UnityEngine;
using System.Collections;

public class Done_BGScroller : MonoBehaviour
{
    public float scrollSpeed;
    public float tileSizeZ;

    private Vector3 startPosition;

    void Start ()
    {
        startPosition = transform.position;
    }

    void Update ()
    {
        float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeZ);
        transform.position = startPosition + Vector3.forward * newPosition;
    }
}

OffsetScroller

Code snippet

using UnityEngine;
using System.Collections;

public class OffsetScroller : MonoBehaviour {

    public float scrollSpeed;
    private Vector2 savedOffset;

    void Start () {
        savedOffset = renderer.sharedMaterial.GetTextureOffset ("_MainTex");
    }

    void Update () {
        float y = Mathf.Repeat (Time.time * scrollSpeed, 1);
        Vector2 offset = new Vector2 (savedOffset.x, y);
        renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset);
    }

    void OnDisable () {
        renderer.sharedMaterial.SetTextureOffset ("_MainTex", savedOffset);
    }
}

StripScroller

Code snippet

using UnityEngine;
using System.Collections;

public class StripScroller : MonoBehaviour {
    
    public float scrollSpeed;
    public float tileSizeZ;

    private Vector2 savedOffset;
    private Vector3 startPosition;
    
    void Start ()
    {
        startPosition = transform.position;
        savedOffset = renderer.sharedMaterial.GetTextureOffset ("_MainTex");
    }
    
    void Update ()
    {
        float x = Mathf.Repeat (Time.time * scrollSpeed, tileSizeZ * 4);
        x = x / tileSizeZ;
        x = Mathf.Floor (x);
        x = x / 4;
        Vector2 offset = new Vector2 (x, savedOffset.y);
        renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset);
        float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeZ);
        transform.position = startPosition + Vector3.back * newPosition;
    }
    
    void OnDisable () {
        renderer.sharedMaterial.SetTextureOffset ("_MainTex", savedOffset);
    }
}

Related tutorials

Related documentation