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

public class PlayerController : MonoBehaviour
{
    Rigidbody2D rb;            // 리디즈바디형 변수
    float axisH = 0.0f;        // 키보드 좌우방향 입력
    public float speed = 3.0f; // 이동속도
    public float jump = 9.0f;  // 점프력

    public LayerMask groundLayer; // 착지할 수 있는 지면 레이어형 변수

    bool goJump = false;   // 점프 개시 플래그
    bool onGround = false; // 지면에 서 있는 플래그

    // 애니메이션처리
    Animator animator;     // 애니메이터 컴포넌트형 변수
    public string stopAnime = "PlayerStop";
    public string moveAnime = "PlayerMove";
    public string jumpAnime = "PlayerJump";
    public string goalAnime = "PlayerGoal";
    public string deadAnime = "PlayerOver";

    string nowAnime = "";
    string oldAnime = "";


    void Start()
    {
        // 리지드바디 컴포넌트 가져오기
        rb = GetComponent<Rigidbody2D>();
        // 충돌시 회전 금지
        rb.constraints = RigidbodyConstraints2D.FreezeRotation; // rb.freezeRotation = true;

        // 애니메이션 처리
        animator = GetComponent<Animator>();
        nowAnime = stopAnime;
        oldAnime = stopAnime;
    }

    // 키보드가 계속 눌렸는지 감지(물리력없음)
    void Update()
    {
        axisH = Input.GetAxisRaw("Horizontal"); // +1, -1, 0 중에 하나
        if(axisH > 0)
        {
            transform.localScale = new Vector2(1, 1);
        }
        else if(axisH < 0)
        {
            transform.localScale = new Vector3(-1, 1); // 좌우반전
        }
        if(Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    // 실제 이동(물리력)
    void FixedUpdate()
    {
        // 착지 판정
        onGround = Physics2D.Linecast(transform.position, transform.position - (transform.up * 0.1f), groundLayer);

        // 지면위에 있을 때(onGround가 참일때) 또는(||) 좌우방향키 눌렸을때 - 좌우이동 가능
        // 지면위에 있으면서 점프키가 눌렸을 때 - 점프가능
        if(onGround || axisH != 0)
        {
            rb.velocity = new Vector2(axisH * speed, rb.velocity.y);
        }
        if(onGround && goJump)
        {
            rb.AddForce(new Vector2(0, jump), ForceMode2D.Impulse);
            goJump = false;
        }
        if(onGround) // 지면위-대기, 이동
        {
            if(axisH == 0)
            {
                nowAnime = stopAnime;
            }
            else
            {
                nowAnime = moveAnime;
            }
        }
        else // 공중에 있을때-점프
        {
            nowAnime = jumpAnime;
        }
        if(nowAnime != oldAnime)
        {
            oldAnime = nowAnime;
            animator.Play(nowAnime);    // 애니메이션 재생
        }
    }

    // 점프
    void Jump()
    {
        goJump = true;
    }
}