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

public class PlayerController04 : MonoBehaviour{

    public float speed;
    public float maxSpeed;
    public float jumpForce;
    public GameObject death;
    public GameObject particles;
    bool jump;
    bool grounded;

    Camera mainCamera;
    Rigidbody2D rb2d;

    // Start is called before the first frame update
    void Start(){
        rb2d = GetComponent<Rigidbody2D>();
        mainCamera = Camera.main;
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetKeyDown(KeyCode.Space) && grounded){
            jump = true;
        }
    }

    void FixedUpdate(){
        if (jump){
            rb2d.velocity = new Vector2(rb2d.velocity.x, 0);
            rb2d.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
            jump = false;
        }
        rb2d.AddForce(Vector2.right * speed);
        rb2d.velocity = new Vector2(Mathf.Clamp(rb2d.velocity.x, -maxSpeed, maxSpeed), rb2d.velocity.y);
    }

    void LateUpdate(){
        mainCamera.transform.position = new Vector3(transform.position.x + 1.5f, mainCamera.transform.position.y, mainCamera.transform.position.z);
    }

    void OnCollisionStay2D(Collision2D col){
        grounded = true;
    }
    void OnCollisionEnter2D(Collision2D col){
        if (col.gameObject.tag == "Damage"){
            AudioManager.instance.Play("Hit");
            Time.timeScale = 0f;
            GetComponent<SpriteRenderer>().enabled = false;
            particles.SetActive(true);
            StartCoroutine(Death());
        }
    }

    IEnumerator Death(){
        yield return new WaitForSecondsRealtime(1f);
        death.SetActive(true);
        yield return new WaitForSecondsRealtime(4f);
        FindObjectOfType<GameController>().LoseGame();
    }

    void OnCollisionExit2D(Collision2D col){
        grounded = false;
    }
}
