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

public class TrajectorySimulation : MonoBehaviour
{
   // public TouchControl Touch_Control;

    public LineRenderer sightLine;
    public PlayerFire playerFire;
    public int segmentCount = 200;
    public float segmentScale = 1;
    
    private Collider _hitObject;

    public Material mat;
    public Collider hitObject {
        get 
        {
            return _hitObject;
        }
    }
    private float AngeleLine=60 ;
    void Awake()
    {
       sightLine.material = mat;

    }

    void FixedUpdate()
    {
        simulatePath();
    }

    void simulatePath() 
    {
        Vector3[] segments = new Vector3[segmentCount];
        segments[0] = playerFire.transform.position;
        Vector3 segVelocity = new Vector3(0,Mathf.Tan(AngeleLine*(Mathf.PI*2/360)),1) * playerFire.fireStrength * Time.deltaTime;
        _hitObject = null;
        for (int i =1;i <segmentCount;i++) 
        {
            float segTime = (segVelocity.sqrMagnitude != 0) ? segmentScale / segVelocity.magnitude : 0;
            segVelocity = segVelocity + Physics.gravity * segTime;
            RaycastHit hit;
            if (Physics.Raycast(segments[i - 1], segVelocity, out hit, segmentScale))
            {
                _hitObject = hit.collider;
               
                segments[i] = segments[i - 1] + segVelocity.normalized * hit.distance;
                segVelocity = segVelocity - Physics.gravity * (segmentScale - hit.distance) / segVelocity.magnitude;
             //   segVelocity = Vector3.Reflect(segVelocity, hit.normal);

            }
            else 
            {
                segments[i] = segments[i - 1] + segVelocity * segTime;
            }
        }
        Color startColor = playerFire.nextColor;
        Color endColor = playerFire.EndColor;
     // sightLine.SetColors(startColor,endColor);
        sightLine.startColor = startColor;
         sightLine.endColor = endColor;


     //   sightLine.SetVertexCount(segmentCount);
        sightLine.positionCount = segmentCount;
        for (int i=0;i <segmentCount;i++) 
        {
            sightLine.SetPosition(i,segments[i]);
        }
    }

  
  
    void Update()
    {
        
    }
}
