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

public class FloorController : MonoBehaviour
{
    private GameObject floorTile1;
    private GameObject floorTile2;

    public GameObject floor;

    public GameObject[] tiles;

    void Start()
    {
        floorTile1 = Instantiate(tiles[0], floor.transform);
        floorTile2 = Instantiate(tiles[Random.Range(0, tiles.Length)], floor.transform);
        floorTile2.transform.position += new Vector3(16f, 0f, 0f);
    }

    void FixedUpdate()
    {
        if (!GameManager.instance.inGame)
        {
            return;
        }
        
        floorTile1.transform.position -= new Vector3(GameManager.instance.worldScrollingSpeed, 0f, 0f);
        floorTile2.transform.position -= new Vector3(GameManager.instance.worldScrollingSpeed, 0f, 0f);

        if (floorTile2.transform.position.x < 0f)
        {
            floorTile1.transform.position += new Vector3(32f, 0f, 0f);

            var newTile = Instantiate(tiles[Random.Range(0, tiles.Length)], floorTile1.transform.position, Quaternion.identity, floor.transform);
            Destroy(floorTile1);

            floorTile1 = floorTile2;
            floorTile2 = newTile;
        }
    }
}
