Home>

I was doing parallax and scroll for a platformer but faced the problem of overlapping backgrounds. The concept is this, I have 5 backrounds and each has its own layer, when the character moves, the left background moves to the right and vice versa. However, something went wrong and my background starts to overlap, thereby reducing the overall 3-component background.

Everything is fine at startup

However, moving in one direction or another, overlap begins and the background decreases

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallax: MonoBehaviour
{
    [SerializeField]
    private float backgroundSize;
    [SerializeField]
    private float parallaxSpeed;
    private Transform cameraTransform;
    private Transform [] layers;
    private float viewZone= 5;
    private int leftIndex;
    private int rightIndex;
    private float lastCameraX;
    private void Start ()
    {
        cameraTransform= Camera.main.transform;
        lastCameraX= cameraTransform.position.x;
        layers= new Transform [transform.childCount];
        for (int i= 0; i <
 transform.childCount; i ++)
        {
            layers [i]= transform.GetChild (i);
        }
        leftIndex= 0;
        rightIndex= layers.Length -1;
    }
    private void Update ()
    {
        float deltaX= cameraTransform.position.x -lastCameraX;
        transform.position += Vector3.right * (deltaX * parallaxSpeed);
        lastCameraX= cameraTransform.position.x;
        if (cameraTransform.position.x <
 (layers [leftIndex] .transform.position.x + viewZone))
        {
            ScrollLeft ();
        }
        if (cameraTransform.position.x >
 (layers [rightIndex] .transform.position.x -viewZone))
        {
            ScrollRight ();
        }
    }
    private void ScrollLeft ()
    {
        int lastRight= rightIndex;
        layers [rightIndex] .position= Vector3.right * (layers [leftIndex] .position.x -backgroundSize);
        leftIndex= rightIndex;
        rightIndex--;
        if (rightIndex <
 0)
        {
            rightIndex= layers.Length -1;
        }
    }
    private void ScrollRight ()
    {
        int lastLeft= leftIndex;
        layers [leftIndex] .position= Vector3.right * (layers [rightIndex] .position.x + backgroundSize);
        rightIndex= leftIndex;
        leftIndex ++;
        if (leftIndex== layers.Length)
        {
            leftIndex= 0;
        }
    }
}