using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackgroundLayer : MonoBehaviour
{
    public float parallax;

    private float width;
    private float height;

    private void Start()
    {
        Bounds bounds = gameObject.GetComponent<SpriteRenderer>().bounds;

        width = bounds.size.x;
        height = bounds.size.y;
    }

    public void Scroll(float scrollX, float scrollY)
    {
        // Update layer local position
        // Note: we use local position because the background container follows the main camera movement
        // and we want to add the layer scrolling to the global movement
        float newPosX = transform.localPosition.x - (scrollX * parallax);
        float newPosY = transform.localPosition.y - (scrollY * parallax);

        // Adjust layer offset to create a continuous scrolling
        if (newPosX < -(width / 4))
            newPosX += width / 2;
        else if (newPosX > +(width / 4))
            newPosX -= width / 2;

        if (newPosY < -(height / 4))
            newPosY += height / 2;
        else if (newPosY > +(height / 4))
            newPosY -= height / 2;

        transform.localPosition = new Vector3(newPosX, newPosY, transform.localPosition.z);
    }
}
