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

public class BackGroundCollector : MonoBehaviour { 
    
    private GameObject[] background;
    private GameObject[] foreground;

    private float lastBackground;
    private float lastForeground;


    void Awake() {
        background = GameObject.FindGameObjectsWithTag("Background");
        foreground = GameObject.FindGameObjectsWithTag("Foreground");

        lastBackground = background[0].transform.position.x;
        lastForeground = foreground[0].transform.position.x;

        for (int i = 1; i < background.Length; i++) {

            if (lastBackground < background[i].transform.position.x)
            {

                lastBackground = background[i].transform.position.x;
            }
        }

        for (int i = 1; i < foreground.Length; i++) {

            if (lastForeground < foreground[i].transform.position.x)
            {
                lastForeground = foreground[i].transform.position.x;
            }

        }
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Background") {

            Vector3 temp = collision.transform.position;
            float width = ((BoxCollider2D)collision).size.x;

            temp.x = lastBackground + width;
            collision.transform.position = temp;
            lastBackground = temp.x;

        } else if (collision.tag == "Foreground") {

            Vector3 temp = collision.transform.position;
            float width = ((BoxCollider2D)collision).size.x;
            
            temp.x = lastForeground + width;
            collision.transform.position = temp;
            lastForeground = temp.x;

            
        } else if (collision.tag == "Foreground") {
            Vector3 temp = collision.transform.position;
            float widthP = ((PolygonCollider2D)collision).bounds.size.x;

            temp.x = lastForeground + widthP;
            collision.transform.position = temp;
            lastForeground = temp.x;
        }
    }

}

