Monday 16 October 2017

Unity 2D Infinite Background Scrolling Simplest Way

Watch Video Tutorial
Code for Infinite Background Scrolling IN Unity 2d game.

using UnityEngine;
using System.Collections;
 
public class Scroll : MonoBehaviour
{
 
    public float backGroundSize;
 
    private Transform cameraTransform;
    public Transform[] layers;
 
    private float viewZone = 0;
    private int leftIndex;
    private int rightIndex;
 
    private void Start()
    {
        cameraTransform = Camera.main.transform;   
 
        leftIndex = 0;
        rightIndex = layers.Length - 1;
    }
 
    void Update()
    {
        if (cameraTransform.position.< 
            (layers[leftIndex].transform.position.+ viewZone))
            ScrollLeft();
 
        if (cameraTransform.position.> 
            (layers[rightIndex].transform.position.- viewZone))
            ScrollRight();
    }
 
    private void ScrollLeft()
    {    
        layers[rightIndex].position = new 
           Vector3
           (1f * (layers[leftIndex].position.- backGroundSize), 0f0f);
        leftIndex = rightIndex;
        rightIndex--;
        if (rightIndex < 0)
            rightIndex = layers.Length - 1;
    }
    private void ScrollRight()
    {   
        layers[leftIndex].position = 
            new Vector3
            (1f * (layers[leftIndex].position.+ backGroundSize), 0f10f);
        rightIndex = leftIndex;
        leftIndex++;
        if (leftIndex == layers.Length)
            leftIndex = 0;
    }
}

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice tutorial. Thanks for sharing the code.
    On Scrolling right there was a flickering and i get fixed by modifying your ScrollRight() code as below:

    private void ScrollRight()
    {
    layers[leftIndex].position =
    new Vector3
    (1f * (layers[rightIndex].position.x + backGroundSize), 0f, 0f);
    rightIndex = leftIndex;
    leftIndex++;
    if (leftIndex == layers.Length)
    leftIndex = 0;
    }

    ReplyDelete