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

public class Jumping : MonoBehaviour
{
    public float Force;
    public AnimationCurve ForceCurve;
    public float JumpDuration;
    public float Cooldown;
    public bool IsJumping;
    public bool CoolingDown;
    public bool IsGrounded;

    private Rigidbody2D _rb;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        IsGrounded = true;
    }



    void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetKeyDown("space") && !IsJumping && !CoolingDown && IsGrounded)
        {
            StartCoroutine(JumpRoutine());
        }

    }

    void FixedUpdate()
    {
    }

    IEnumerator JumpRoutine()
    {
        IsJumping = true;
        IsGrounded = false;
        var jumpStart = Time.time;
        while (Time.time < jumpStart + JumpDuration)
        {
            if (!Input.GetKey("space"))
                break;
            yield return new WaitForFixedUpdate();
            _rb.AddForce(Vector2.up*Force*ForceCurve.Evaluate((Time.time-jumpStart)/JumpDuration)*Time.fixedDeltaTime, ForceMode2D.Force);
        }
        CoolingDown = true;
        IsJumping = false;
        yield return new WaitForSeconds(Cooldown);
        CoolingDown = false;

    }
}
