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

public class Worm : MonoBehaviour
{
    public LineRenderer line;
    public float length;
    public float wriggleSpeed;

    int wriggleFrame = 0;
    int offset = 0;
    Quaternion direction = Quaternion.identity;

    // Start is called before the first frame update
    void Start()
    {
        GameObject ground = GameObject.Find("ground");
        Physics2D.IgnoreCollision(gameObject.GetComponent<PolygonCollider2D>(), ground.GetComponent<BoxCollider2D>());

        wriggleFrame = 0;
        offset = Random.Range(0, 100);
        direction = Quaternion.Euler(0, 0, (float)Random.Range(-30, 30));
    }

    // Update is called once per frame
    void Update()
    {
        wriggleFrame++;

        //direction = direction * Quaternion.Euler(0, 0, Random.value - 1f);

        Vector3[] positions = new Vector3[line.positionCount];
        float segmentLength = (length / line.positionCount);
        float wriggleAmount = length * 0.05f;

        for (int i = 0; i < line.positionCount; i++)
        {
            float l = i * segmentLength;

            Vector3 p = direction * (l * Vector3.right + wriggleAmount * Mathf.Cos(((i + offset) + (wriggleFrame * wriggleSpeed)) / 2) * Vector3.up);
            positions[i] = p;
        }
        line.SetPositions(positions);

    }
}
