using UnityEngine;

public class TreadsGenerator : MonoBehaviour
{
    public GameObject treadPiece;
    public Vector3 worldOffset;
    public float z;
    public float y;
    public float piecesDistance;

    // Start is called before the first frame update
    void Start()
    {
        SpawnTreads();
    }

    void SpawnTreads()
    {
        GameObject[] treadClones = new GameObject[(int)(z * y)];
        int i;
        int j;

        for (i = 0; i < z; i++)
        {
            for (j = 0; j < y; j++)
            {
                if(i==0 || i==z-1 || j==0 || j==y-1)
                {
                    Vector3 spawnPosition = new Vector3(0, j * treadPiece.transform.localScale.z * piecesDistance, i * treadPiece.transform.localScale.z * piecesDistance) + this.transform.position + worldOffset;
                    Quaternion spawnRotation = Quaternion.identity;

                    GameObject treadClone = Instantiate(treadPiece, spawnPosition, spawnRotation);
                    treadClone.name = "Tread" + i + "_" + j;

                    treadClones[i * (int)y + j] = treadClone;
                }
            }
        }

        for(i=0;i<=z;i++)
        {
            for(j=0;j<=y;j++)
            {
                if(j>=0 && j<=z-1 && (i==0))
                {

                    HingeJoint currentHingeJoint = treadClones[i].GetComponent<HingeJoint>();
                    HingeJoint nextHingeJoint = treadClones[i+1].GetComponent<HingeJoint>();

                    if (currentHingeJoint != null && nextHingeJoint != null)
                    {
                        currentHingeJoint.connectedBody = nextHingeJoint.GetComponent<Rigidbody>();
                    }
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        // Add any update logic if needed
    }
}