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

public class backgroundRepeater : MonoBehaviour
{
    public Transform prefab;
    Vector3 cameraOffset;
    float pixelsPerUnit;
    float scale;
    int backgroundTilesX;
    int backgroundTilesY;

    void Start()
    {
        CalculateCameraOffset();
        CalculateBackgroundTilesNeeded();
        CreateGameObjects();
    }

    void CalculateCameraOffset()
    {
        cameraOffset = Camera.main.ScreenToWorldPoint(Vector3.zero) + new Vector3(0, 1, 10);
    }

    void CalculateBackgroundTilesNeeded()
    {
        SpriteRenderer spriteRenderer = prefab.GetComponent<SpriteRenderer>();
        pixelsPerUnit = spriteRenderer.sprite.pixelsPerUnit;
        scale = spriteRenderer.transform.localScale.x;
        backgroundTilesX = (int)(Screen.width / (pixelsPerUnit * scale)) + 1;
        backgroundTilesY = (int)(Screen.height / (pixelsPerUnit * scale)) + 1;
    }

    void CreateGameObjects()
    {
        for (int x = 0; x < backgroundTilesX; x++)
        {
            CreateGameObject(x);

            for (int y = 0; y < backgroundTilesY; y++) CreateGameObject(x, y);
        }
    }

    void CreateGameObject(float x = 0, float y = 0)
    {
        Instantiate(prefab, new Vector3(x * scale, y * scale, 0) + cameraOffset, Quaternion.identity);
    }
}


