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

public class CharacterMovement : MonoBehaviour
{
    [SerializeField] protected float _moveSpeed=5f;
    [SerializeField] protected float _acceleration = 16f;
    [SerializeField] protected float _airAcceleration = 16f;
    [SerializeField] protected float _friction = 16f;
    [SerializeField] protected float _gravity = 20f;
    [SerializeField] protected float _stickForce = 5f;
    [SerializeField] protected float _jumpForce = 10f;
    protected CharacterController _cc;
    protected bool _wishJump;
    protected float _currentGravity;
    protected Vector3 _velocity;
    protected Vector3 _wishInput;

    public Vector3 velocity
    {
        get
        {
            return _velocity;
        }
    }

    public float currentGravity
    {
        get
        {
            return _currentGravity;
        }
    }

    private void Awake()
    {
        _cc = GetComponent<CharacterController>();
    }

    public void Jump()
    {
        if (_cc.isGrounded)
            _wishJump = true;
    }

    public void SetInput (Vector3 wishdir)
    {
        _wishInput = wishdir.normalized;
    }

    private void Update()
    {
        FinishGravity();
        Move();
    }

    void FinishGravity()
    {
        if (_cc.isGrounded)
        {
            _currentGravity = -_stickForce;
        }
        else
        {
            _currentGravity -= _gravity * Time.deltaTime;
        }
        if (_wishJump)
            _currentGravity = _jumpForce;
        _wishJump = false;
    }

    private void Move()
    {
        Vector3 wishVelocity = _wishInput * _moveSpeed;
        float lerpT = _cc.isGrounded ? (wishVelocity.magnitude >= _velocity.magnitude ? _acceleration : _friction) : _airAcceleration;
        _velocity = Vector3.Lerp(_velocity, wishVelocity, Time.deltaTime * lerpT);
        _cc.Move(_velocity * Time.deltaTime + _currentGravity * Vector3.up * Time.deltaTime);
    }
}