using UnityEngine;

public class deadBody : MonoBehaviour
{
    //hej
    public GameObject explosion;
    private Vector3 Mgoal;
    private Vector2 MDir;
    Rigidbody2D rig;
    public float radie = 0.1f;
    float halfdistance;
    private float mStartSpeed;
    private float mSpeed;
    private Vector2 mHalfDistancePos;
    public Transform sprite;
    private Vector3 mOriginalScale;
    private bool flying;

    private Vector3 startPosition; //Used to check if we passed the target
    bool rotateLeft;
    float rotationSpeed;

    public void setGoal(Vector3 _goal, float speed)
    {
        flying = true;
        Mgoal = _goal;
        mStartSpeed = speed;
        Vector3 dir = (_goal - gameObject.transform.position);
        MDir = new Vector2(dir.x, dir.y);
        mHalfDistancePos = (Vector2)gameObject.transform.position + (MDir * 0.5f);
        halfdistance = Vector2.Distance(gameObject.transform.position, mHalfDistancePos);
        MDir = MDir.normalized;
    }

    // Use this for initialization
    void Start()
    {
        rig = GetComponent<Rigidbody2D>();
        mOriginalScale = sprite.localScale;
        startPosition = transform.position;
        rotationSpeed = Random.Range(-100, 100);
        int random = Random.Range(0, 9);
        Sprite[] _sprite = Resources.LoadAll<Sprite>("Dead People/");
        sprite.GetComponent<SpriteRenderer>().sprite = _sprite[random];

    }

    // Update is called once per frame
    void Update()
    {
        if(rotationSpeed < 10 && rotationSpeed> -10)
            rotationSpeed = Random.Range(-100, 100);

        //Check if we passed the goal
        if (Vector2.Distance(transform.position, startPosition) > Vector2.Distance(Mgoal, startPosition))
        {
            AudioManager.instance.PlayImpactSound();
            Instantiate(explosion, gameObject.transform.position, Quaternion.identity);
            Destroy(gameObject);
        }

        //if the distance is smaller than the half start distance
        //throwing arc
        if (flying)
        {
            float percent = Vector2.Distance(gameObject.transform.position, mHalfDistancePos) / halfdistance;
            sprite.localScale = mOriginalScale + mOriginalScale * (1 - percent);
            percent = Mathf.Clamp(percent, 0.5f, 1f);

            mSpeed = mStartSpeed * percent;

            rig.velocity = MDir * mSpeed;
            transform.Rotate(0, 0, rotationSpeed * Time.deltaTime);
        }

    }

    void OnDestroy()
    {
        Camera.main.GetComponent<ScreenShake>().setShake(0.1f);
    }
}
