using UnityEngine;

public class CharacterControlle2D : MonoBehaviour
{
    [SerializeField] private float jumpForce = 400f;
    private float movementSmoothing = .05f;
    [SerializeField] private LayerMask whatIsGround;
    [SerializeField] private CircleCollider2D groundCheck;

    private bool grounded;
    private Rigidbody2D rb2D;
    private bool facingRight = true;
    private Vector3 currentVelocity = Vector3.zero;

    private void Awake()
    {
        rb2D = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        if(groundCheck != null)
        {
            grounded = false;

            Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.transform.position, groundCheck.radius, whatIsGround);
            for (int i = 0; i < colliders.Length; i++)
            {
                if(colliders[i].gameObject != gameObject)
                {
                    grounded = true;
                }
            }
        }
        else
        {
            grounded = true;
        }
    }

    public void Move(float move, bool jump = false)
    {
        Vector3 targetVelocity = new Vector2(move * 10f, rb2D.velocity.y);

        rb2D.velocity = Vector3.SmoothDamp(rb2D.velocity, targetVelocity, ref currentVelocity, movementSmoothing);

        if(move > 0 && !facingRight)
        {
            Flip();
        }

        else if(move < 0 && facingRight)
        {
            Flip();
        }

        if(grounded && jump) {
            grounded = false;
            rb2D.AddForce(new Vector2(0f, jumpForce));
        }
    }

    private void Flip()
    {
        facingRight = !facingRight;
        
        Vector3 currentScale = gameObject.transform.localScale;
        currentScale.x *= -1;
        gameObject.transform.localScale = currentScale;

    }
}
