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

[ExecuteInEditMode]
public class vine : MonoBehaviour
{
    private LineRenderer lineRenderer;

    [SerializeField]
    private GameObject position1;
    [SerializeField]
    private GameObject position2;

    private Vector3 lastPosition1;
    private Vector3 lastPosition2;
    private float lastDipMagnitude;
    private int lastNumberPoints;

    [SerializeField]
    private AnimationCurve vineCurve;
    [SerializeField]
    private float dipMagnitude = 1f;
    [SerializeField]
    private int numberOfPoints = 20;

    // Start is called before the first frame update
    void Awake()
    {
        lineRenderer = GetComponent<LineRenderer>();
    }

    void Update()
    {
        //if both positions are defined
        if (position1 != null && position2 != null)
        {
            //if either of the points have moved
            if ((position1.transform.position != lastPosition1) || (position2.transform.position != lastPosition2) || (dipMagnitude != lastDipMagnitude) || (numberOfPoints != lastNumberPoints))
            {
                Recalculate();
            }
        }
    }

    [ContextMenu("Recalculate")]
    void Recalculate()
    {
        lineRenderer.positionCount = numberOfPoints;

        //set start and end
        lineRenderer.SetPosition(0, position1.transform.position);
        lineRenderer.SetPosition(lineRenderer.positionCount-1, position2.transform.position);

        for (int i = 0; i<lineRenderer.positionCount; i++)
        {
            Vector3 newLerpPos = Vector3.Lerp(position1.transform.position, position2.transform.position, i / (float)(lineRenderer.positionCount - 1));
            Vector3 newDip = Vector3.up * dipMagnitude * (1f - vineCurve.Evaluate(i / (float)(lineRenderer.positionCount - 1)));


            lineRenderer.SetPosition(i, newLerpPos - newDip);
        }

        lastPosition1 = position1.transform.position;
        lastPosition2 = position2.transform.position;
        lastDipMagnitude = dipMagnitude;
        lastNumberPoints = numberOfPoints;
}
}
